Child to parent communication in React (JSX) without flux

為{幸葍}努か 提交于 2019-11-30 13:27:44

The callback function should work. As you've mentioned in your previous comment you can use your captured this to access the updateColor function from the child:

var passTarget = this;
...
...
return <ColorButton 
  buttonColor={object} 
  key={i} 
  update={passTarget.updateColor} />

Or as Bogdan mentioned you can pass it through map after your callback function:

{colorsArray.map(function(object, i){
  return <ColorButton 
           buttonColor={object} 
           key={i} 
           update={this.updateColor} />;
}, this)}

Your <ColorButton /> component should then be able to run a simple onClick function:

onClick={this.props.update}

And then you can simply make use of normal event targets in the parent component to capture the color of the button that was clicked:

updateColor: function(e) {
  console.log(e.target.style.backgroundColor);
}

Here is a full DEMO to demonstrate.

You can just pass callback function into child from your parent component, as simple as this:

 <ColorButton buttonColor={object} key={i} onColorSelect={this.updateColor}/>

(when using React.createClass all class methods are already bound to this, so you are not required to call .bind(this)).

Then from ColorButton component you can call this callback as this.props.onColorSelect(...).

JS Bin example: http://jsbin.com/fivesorume/edit?js,output

OK, this is pretty simple in React without using flux or redux, similar to passing down props from parent to child, here we can use callback function like this:

var colorsArray = ["#ED5851", "#9CCC64", "#337AEC", "#ff7a45", "#7E58C2", "#FFEB3B", "#78909C", "#FFFFFF", "#213a4b"];


var EditDrawer = React.createClass({
    updateColor: function(i) {
        alert("New Color: " + i);
    },
    render: function(){
        return (
            <div className="container-fluid animated fadeIn extra-fast-animation tag-edit-drawer">
                <div className="row">
                    <div className="col-xs-12">
                        {colorsArray.map(function(object, i){
                            return <ColorButton buttonColor={object} key={i} updateColor={this.updateColor}/>;
                        }, this)}
                    </div>
                </div>
            </div>
        );
    }
});


var ColorButton = React.createClass({
    updateColor: function() {
        this.props.updateColor(this.props.buttonColor);
    },
    render: function(){
        var buttonStyle = {
            backgroundColor: this.props.buttonColor,
        };
        return (
            <div className="tag-edit-color-button" 
            style={buttonStyle}
            onClick={this.updateColor}>
              this.props.buttonColor
            </div>
        )
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!