如何在React.js中将道具从一个类传递到另一个类 [英] How to pass props from one class to another in React.js

查看:50
本文介绍了如何在React.js中将道具从一个类传递到另一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对React非常陌生。我正在通过创建一个非常简单的九格框进行练习,用户可以在其中使用下拉菜单选择他们现在要使用的颜色。唯一的是,我还不太清楚如何将变量从包含变量的类(ColorPicker)传递到包含网格的类(Box)。谁能给我一些如何做的指示?

I'm very new to React. I'm practicing by creating a very simple nine grid box, where a user can select what color they want to use at the moment by using a dropdown menu. The only thing is, I can't quite figure out how to pass the variable from the class that contains it (ColorPicker) to the class that contains the grids (Box). Can anyone give me some pointers on how to do this?

我仍然习惯于将道具传递给其他类。

I'm still getting used to passing props to other classes.

这里是链接到CodePen: http://codepen.io/anfperez/pen/RorKge

Here's a link to the 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中的道具从父项传递给子项。例如,如果您有一个呈现子类的父类,则该父类现在可以将prop传递给子类。这是一个例子。

Props in React get passed from the parent to the child. For instance, If you have a parent class which renders a child class, the parent class can now pass props to the child class. Here is an example.

class Parent extends React.Component {
    render() {
        return (
            <Child example="foo" />
        )
    }
}

class Child extends React.component {
    render() {
        return (
            <h1>{this.props.example}</h1>
        )
    }
}

父类呈现子类。父类将一个传递给孩子的道具称为example。在孩子中,您可以通过调用 this.props.example

The parent class renders the child class. The parent class passes a prop to child called example. In child you can have access to the value of child by calling this.props.example

这篇关于如何在React.js中将道具从一个类传递到另一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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