2018
08.10

例如,我们要定义一个组件CarView。数据用一个类Car来表示,Car有以下的属性:id, name, color。

class Car {

constructor(id, name, color) {

this.id = id;

this.name = name;

this.color = color;

}

}

我们在CarView的上级组件的state里有一个Car类型的对象car,想把car的属性的值传给CarView组件去渲染界面,这时候可以采用如下的传递参数的方法:

<CarView {…this.state.car} />

在CarView定义里可以使用this.props.id, this.props.name, this.props.color来获得传递进来的参数。如:

在CarView的render方法里:

<Text>{this.props.name}</Text>,可以渲染出car的name。

以上的写法相当于<CarView id={this.state.car.id} name={this.state.car.name}  color={this.state.car.color} />。

可见这种写法使代码得以简化。

回复功能关闭


Hit Counter by http://yizhantech.com/