配置子组件功能将多个参数传递给父函数?

时间:2016-10-29 15:37:24

标签: javascript reactjs

如何配置子组件单击事件以便父函数可以获取所需的参数,有时父函数将需要1个参数,有时需要2个等等?

儿童组件 的 JS

export default React.createClass({
    render() {
        return (
            <div class="ticker">
                <button class="ticker__tick ticker__tick--up btn btn--secondary state--bg" disabled={this.props.disabled ? this.props.disabled : false} onClick={() => this.props.handleClick('up')}>&nbsp;</button>
                <input class="ticker__value text--center soft-half flush--bottom" type="text" name="{this.props.tickerValueName}" value={this.props.value} readOnly />
                <button class="ticker__tick ticker__tick--down btn btn--secondary state--bg" disabled={this.props.disabled ? this.props.disabled : false} onClick={() => this.props.handleClick('down')}>&nbsp;</button>
            </div>
        )
    }
});

this.props.handleClick可能指向function(param1, param2)function(param1)

1 个答案:

答案 0 :(得分:0)

相反传递单个参数,将整个参数作为对象传递,并访问父对象中该对象的属性。

//parent
function handleClick(obj){
 var param1 = obj.param1
 var param2 = obj.param2
 ...
}

//children
onClick={() => this.props.handleClick({param1: 'down'})}
onClick={() => this.props.handleClick({param1: 'down', param2: 'up'})}

因此,参数的数量总是一个。

希望这有帮助!