简体   繁体   English

React.js道具分配问题

[英]React.js Props assignmend questions

Hey guys i have one questions about props, something i dont quite understand: 大家好,我对道具有一个疑问,我不太了解:

lets say i have the main component named App and a Header component: 可以说我有一个名为App的主要组件和一个Header组件:

In the App i have some html with 在应用程序中,我有一些html

and in the Header component i have something like: 在Header组件中,我有类似以下内容:

Your name is {this.props.name}, your age is {this.props.age} 您的名字是{this.props.age},您的年龄是{this.props.age}

What i dont understand is where are the props assigned and where used. 我不明白的是在哪里分配道具和在哪里使用。 Does the name={"Max"} assigns the props or the this.props.name assigns the props and then name={"max"} uses it I'm not sure if i explain it correctly but i dont get the directions of the assignment. 是name = {“ Max”}分配道具还是this.props.name分配道具,然后name = {“ max”}使用道具,我不确定我是否正确解释了,但没有得到指示分配。

If the header component is inheriting from the App component, then it gets its props from the App component. 如果标头组件是从App组件继承的,则它从App组件获取其道具。

In your App component you can define those props from its this.state, then assign those states to your header component as a property. 在您的App组件中,您可以从其this.state定义这些道具,然后将这些状态作为属性分配给标头组件。

For example: 例如:

class App extends Component {
  constructor( props ) {
    super( props );
    this.state = {
      age: 45,
      name: 'Robert'
    }
  }
  render() {
    return (
      <div>
        <Header ageOfPerson={this.state.age} nameOfPerson={this.state.name} />
      </div>
    );
  }

  class Header extends Component {
    constructor( props ) {
      super( props );
    }
    render() {
      <div>
        <p>{ this.props.ageOfPerson } is { this.props.nameOfPerson }s age.</p>
      </div>
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM