react 渲染道具_React中的道具与状态

react 渲染道具

In a React component, props are variables passed to it by its parent component. State on the other hand is still variables, but directly initialized and managed by the component.

在React组件中, props是其父组件传递给它的变量。 另一方面, 国家仍然是变量,而是直接初始化和组件管理。

The state can be initialized by props.

状态可以通过props初始化。

For example, a parent component might include a child component by calling

例如,父组件可以通过调用来包括子组件

<ChildComponent />

The parent can pass a prop by using this syntax:

父母可以使用以下语法传递道具:

<ChildComponent color=green />

Inside the ChildComponent constructor we could access the prop:

在ChildComponent构造函数中,我们可以访问prop:

class ChildComponent extends React.Component {
  constructor(props) {
    super(props)
    console.log(props.color)
  }
}

and any other method in this class can reference the props using this.props.

并且此类中的任何其他方法都可以使用this.props引用道具。

Props can be used to set the internal state based on a prop value in the constructor, like this:

道具可用于基于构造函数中的道具值设置内部状态,如下所示:

class ChildComponent extends React.Component {
  constructor(props) {
    super(props)
    this.state.colorName = props.color
  }
}

Of course a component can also initialize the state without looking at props.

当然,组件也可以在不查看道具的情况下初始化状态。

In this case there’s nothing useful going on, but imagine doing something different based on the prop value, probably setting a state value is best.

在这种情况下,没有任何用处,但可以想象根据prop值做一些不同的事情,最好设置一个状态值。

Props should never be changed in a child component, so if there’s something going on that alters some variable, that variable should belong to the component state.

子组件中的道具永远不应更改,因此,如果发生某些事情改变了某些变量,则该变量应属于组件状态。

Props are also used to allow child components to access methods defined in the parent component. This is a good way to centralize managing the state in the parent component, and avoid children to have the need to have their own state.

道具还用于允许子组件访问父组件中定义的方法。 这是在父组件中集中管理状态的一种好方法,可以避免子级需要拥有自己的状态。

Most of your components will just display some kind of information based on the props they received, and stay stateless.

您的大多数组件只会根据收到的道具显示某种信息,并且保持无状态

翻译自: https://flaviocopes.com/react-state-vs-props/

react 渲染道具

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值