2016-03-29 100 views
0

我正在玩reactjs和svg。我試圖將App中的多個元素狀態傳遞給Circle。有沒有通過它一氣呵成的一種方式,而不是reactjs傳遞多個元素

<Circle h={this.state.h} w={this.state.w} and so on /> 

請參見下面的代碼:

class Circle extends React.Component { 
    render() { 
    return (
     <svg height="100" width="100"> 
     <circle cx="50" cy="50" r="40" 
      stroke="black" stroke-width="3" fill="red" 
     /> 
     </svg> 
    ) 
    } 
} 

class App extends React.Component { 
    constructor(props) { 
    super(props) 
    this.state = { 
     h: 100, 
     w: 100, 
     cx: 50, 
     cy: 50, 
     r: 40, 
     stroke: "black", 
     fill: "red" 
    } 
    } 
    render() { 
    return (
     <div> 
     <Circle /> 
     </div> 
    ) 
    } 
} 

ReactDOM.render(<App />, document.getElementById('app')) 
+2

'<圈{...} this.state />' – azium

回答

3

Use ES6 spread operator:

render() { 
    return (
     <div> 
     <Circle {...this.state} /> 
     </div> 
    ) 
} 

中然後在Circle:

class Circle extends React.Component { 
    render() { 
    const { h, x, y, w, r, stroke, fill } = this.props; 
    return (
     <svg height={h} width={w}> 
     <circle cx={x} cy={y} r={r} 
      stroke={stroke} stroke-width="3" fill={fill} 
     /> 
     </svg> 
    ) 
    } 
} 
1

當然

const props = { 
    w: this.state.w, 
    h: this.state.h, 
    ... 
} 

<Circle {...props} /> 

// or pass content of `state` 
<Circle {...this.state} /> 
1

你可以!在對象上使用ES2015傳播運算符。 (更多關於在JSX here

使用會看你的代碼,如:

class Circle extends React.Component { 
    constructor (props) { 
    super(props) 
    console.log(this.props) 
    } 
    render() { 
    return (
     <svg height="100" width="100"> 
     <circle cx="50" cy="50" r="40" 
      stroke="black" stroke-width="3" fill="red" 
     /> 
     </svg> 
    ) 
    } 
} 

class App extends React.Component { 
    constructor() { 
    super() 
    this.state = { 
     h: 100, 
     w: 100, 
     cx: 50, 
     cy: 50, 
     r: 40, 
     stroke: "black", 
     fill: "red" 
    } 
    } 
    render() { 
    return (
     <div> 
     <Circle {...this.state}/> 
     </div> 
    ) 
    } 
} 

ReactDOM.render(<App />, document.getElementById('app'))