reactjs传递多个元素

reactjs pass multiple elements

本文关键字:元素 reactjs      更新时间:2023-09-26

我在玩reactjs和svg。我正在尝试将多个元素状态从应用程序传递到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'))

使用ES6排列运算符:

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

然后在圆圈中:

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> 
    )
  }
}

当然是

const props = {
  w: this.state.w,
  h: this.state.h,
  ...
}
<Circle {...props} />
// or pass content of `state`
<Circle {...this.state} />

您可以!对对象使用ES2015排列运算符。(更多关于JSX这里)

您使用的代码看起来像:

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'))