React中的状态和道具有什么区别? [英] What is the difference between state and props in React?

查看:182
本文介绍了React中的状态和道具有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在看React的Pluralsight课程,导师说道具不应该改变。我现在正在阅读一篇文章(uberVU / react-guide)关于道具与状态,它说

I was watching a Pluralsight course on React and the instructor stated that props should not be changed. I'm now reading an article (uberVU/react-guide) on props vs. state and it says


道具和状态更改都会触发渲染更新。

Both props and state changes trigger a render update.

文章后面说:


道具(属性的简称)是一个组件的配置,如果可能的话,它的选项。它们是从上面接收的并且是不可变的。

Props (short for properties) are a Component's configuration, its options if you may. They are received from above and immutable.




  • 所以道具可以改变但它们应该是不可变的吗?

  • 你什么时候应该使用道具?什么时候应该使用州?

  • 如果您有React组件需要的数据,是否应通过道具或React组件中的设置通过 getInitialState

    • So props can change but they should be immutable?
    • When should you use props and when should you use state?
    • If you have data that a React component needs, should it be passed through props or setup in the React component via getInitialState?
    • 推荐答案

      道具与州相关。一个组件的状态通常会成为子组件的支柱。道具在父级的render方法中传递给子级,作为 React.createElement()的第二个参数,或者,如果您使用的是JSX,则更熟悉的标记属性。

      Props and state are related. The state of one component will often become the props of a child component. Props are passed to the child within the render method of the parent as the second argument to React.createElement() or, if you're using JSX, the more familiar tag attributes.

      <MyChild name={this.state.childsName} />
      

      父元素的 childsName 的状态值变为孩子的 this.props.name 。从孩子的角度来看,名称prop是不可变的。如果需要更改,父级应该只更改其内部状态:

      The parent's state value of childsName becomes the child's this.props.name. From the child's perspective, the name prop is immutable. If it needs to be changed, the parent should just change its internal state:

      this.setState({ childsName: 'New name' });
      

      并且React会将它传播给孩子。一个自然的后续问题是:如果孩子需要更改其名称支柱怎么办?这通常通过子事件和父回调来完成。孩子可能会暴露一个名为的事件,例如 onNameChanged 。然后,父母将通过传递回调处理程序来订阅该事件。

      and React will propagate it to the child for you. A natural follow-on question is: what if the child needs to change its name prop? This is usually done through child events and parent callbacks. The child might expose an event called, for example, onNameChanged. The parent would then subscribe to the event by passing a callback handler.

      <MyChild name={this.state.childsName} onNameChanged={this.handleName} />
      

      孩子会通过调用,例如<,将其请求的新名称作为参数传递给事件回调。 code> this.props.onNameChanged('New name'),父母将使用事件处理程序中的名称来更新其状态。

      The child would pass its requested new name as an argument to the event callback by calling, e.g., this.props.onNameChanged('New name'), and the parent would use the name in the event handler to update its state.

      handleName: function(newName) {
         this.setState({ childsName: newName });
      }
      

      这篇关于React中的状态和道具有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆