将参数传递给React中的props函数

哈坎·卡拉杜曼(Hakan Karaduman)

我写了两个示例组件来展示我要做什么。如果呼叫来自同一班,则可以执行以下操作。

onClick={this.myFunc.bind(this, param1, param2)}

我该如何从无状态组件中进行相同的操作而又无需弄乱绑定“ this”。

onClick={props.onClick['need to add params']}

import React from 'react';
 
class BigComponent extends React.Component{
    constructor(props){
        super(props);
        this.handleClick = this.handleClick.bind(this);
    }
    
    handleClick(param1, param2){
        // do something with parameters
    }

    render(){
        return(
            <div>
                <SmallComponent handleClick={this.handleClick}/>
            </div>
        );
    }
}

function SmallComponent(props){
	return(
        <div>
            <button onClick={ () => {props.handleClick('value_1', 'value_2')}}></button>
            <button onClick={ () => {props.handleClick('value_3', 'value_4')}}></button> 
            {/* how to do above without arrow functions, because I read that it's not optimized*/}
        </div>
    );
}

普祖

在中添加回调this.myFunc

this.myFunc = event => (param1, param2) => { ... do stuff }

在顶层组件中,您可以执行以下操作:

handleClick={this.myFunc}

在您的孩子中,只需执行以下操作:

onClick={handleClick(param1, param2)}

希望这会有所帮助。

或者,您可以执行以下操作:

function SmallComponent(props){
    const handleClick = (param1, param2) => (event) => props.handleClick(param1, param2);

    return(
        <div>
            <button onClick={handleClick(param1, param2)}></button>
            ...
    );
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章