内容简介:翻译自:https://stackoverflow.com/questions/40662893/how-to-pass-props-from-one-class-to-another-in-react-js
我对React很新.我正在练习创建一个非常简单的九格网框,用户可以使用下拉菜单选择他们想要使用的颜色.唯一的问题是,我无法弄清楚如何将包含它的类(ColorPicker)中的变量传递给包含网格的类(Box).谁能给我一些关于如何做到这一点的指示?
我还习惯把道具传递给其他班级.
这是CodePen的链接: http://codepen.io/anfperez/pen/RorKge
这是我的代码
//this displays the color selections for the boxes: red, green, and blue
var ColorPicker = React.createClass({
handleChange: function(e) {
var newColor = e.target.value;
this.props.onChange(color);
},
render: function() {
return (
<div>
<select id="pick-colors" onChange={this.handleChange}>
<option value="red">
Red
</option>
<option value="green">
Green
</option>
<option value="blue">
Blue
</option>
</select>
</div>
)
}
});
//contains the boxes that will eventually change color
var Box = React.createClass({
getInitialState: function() {
return {
//boxes are initially white
color: 'white'
};
},
changeColor: function(newColor) {
var newColor = this.state.color;
this.setState({
color: newColor
});
},
render: function() {
return (
<div >
<div className='box' style={{background:this.state.color}} onClick={this.changeColor}>
</div>
</div>
);
}
});
React中的道具从父级传递给子级.例如,如果您有一个呈现子类的父类,则父类现在可以将props传递给子类.这是一个例子.
class Parent extends React.Component {
render() {
return (
<Child example="foo" />
)
}
}
class Child extends React.component {
render() {
return (
<h1>{this.props.example}</h1>
)
}
}
父类呈现子类.父类将prop传递给名为example的子项.在子级中,您可以通过调用this.props.example来访问子级的值
翻译自:https://stackoverflow.com/questions/40662893/how-to-pass-props-from-one-class-to-another-in-react-js
以上所述就是小编给大家介绍的《javascript – 如何在React.js中将道具从一个类传递到另一个类》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- JEEBBS v5.1 发布,道具和交易功能开源
- meteor – react-bootstrap:关于未知道具的警告
- 矩阵分解技术应用于在线游戏道具推荐场景的调研
- python中将list转为dict
- Spring中将header头转换为参数
- 数组 – 如何在Swift中将数组拆分成两半?
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。