我和reactjs和svg一起玩。我试图将多个元素状态从App传递给Circle。有没有办法一次性传递它,而不是
<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'))
答案 0 :(得分:3)
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 :(得分:1)
当然
const props = {
w: this.state.w,
h: this.state.h,
...
}
<Circle {...props} />
// or pass content of `state`
<Circle {...this.state} />
答案 2 :(得分: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'))