Lei*_*ana 9 javascript components class reactjs
我对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>
);
}
});
Run Code Online (Sandbox Code Playgroud)
Cha*_*man 23
React中的道具从父级传递给子级.例如,如果您有一个呈现子类的父类,则父类现在可以将props传递给子类.这是一个例子.
class Parent extends React.Component {
render() {
return (
<Child example="foo" />
)
}
}
class Child extends React.component {
render() {
return (
<h1>{this.props.example}</h1>
)
}
}
Run Code Online (Sandbox Code Playgroud)
父类呈现子类.父类将prop传递给名为example的子项.在孩子中,您可以通过呼叫访问孩子的价值this.props.example
| 归档时间: |
|
| 查看次数: |
27182 次 |
| 最近记录: |