Reactjs 如何通过一个命令获取多个反应按钮文本

Reactjs 如何通过一个命令获取多个反应按钮文本,reactjs,Reactjs,我在一个表单中有多个按钮,我知道我可以使用下面的命令来获取每个按钮的文本值,但是重复代码不是很好和干净,我想知道是否有其他方法可以使用一个变量和一个函数来获取所有按钮的文本值 提前谢谢 btnRef1 = React.createRef(); btnRef2 = React.createRef(); btnRef3 = React.createRef(); getTextValue1 = () => { console.log("getTextValue=> char: "

我在一个表单中有多个按钮,我知道我可以使用下面的命令来获取每个按钮的文本值,但是重复代码不是很好和干净,我想知道是否有其他方法可以使用一个变量和一个函数来获取所有按钮的文本值

提前谢谢

btnRef1 = React.createRef();
btnRef2 = React.createRef();
btnRef3 = React.createRef();

getTextValue1 = () => {
    console.log("getTextValue=> char: ", this.btnRef1.current.textContent);
};
getTextValue2 = () => {
    console.log("getTextValue=> char: ", this.btnRef2.current.textContent);
};
getTextValue]3 = () => {
    console.log("getTextValue=> char: ", this.btnRef3.current.textContent);
};

<MDBBtn innerRef={this.btnRef1} onClick={this.getTextValue1}>
    1
</MDBBtn>
<MDBBtn innerRef={this.btnRef2} onClick={this.getTextValue2}>
    2
</MDBBtn>
<MDBBtn innerRef={this.btnRef3} onClick={this.getTextValue3}>
    3
</MDBBtn>
btnRef1=React.createRef();
btnRef2=React.createRef();
btnRef3=React.createRef();
getTextValue1=()=>{
log(“getTextValue=>char:”,this.btnRef1.current.textContent);
};
getTextValue2=()=>{
log(“getTextValue=>char:”,this.btnRef2.current.textContent);
};
getTextValue]3=()=>{
log(“getTextValue=>char:”,this.btnRef3.current.textContent);
};
1.
2.
3.

如果您只需要将文本传递给函数,您可以执行以下操作:

getTextValue = (value) => {
    console.log("getTextValue=> char: ", value);
};

<MDBBtn onClick={() => this.getTextValue(1)}>1</MDBBtn>
getTextValue=(value)=>{
log(“getTextValue=>char:”,value);
};
this.getTextValue(1)}>1
您还可以对按钮使用循环:

const buttons = [1,2,3];

buttons.map(value => <MDBBtn onClick={() => this.getTextValue(value)}>{value}</MDBBtn>)
const按钮=[1,2,3];
buttons.map(value=>this.getTextValue(value)}>{value})

如果您只需要将文本传递给函数,您可以执行以下操作:

getTextValue = (value) => {
    console.log("getTextValue=> char: ", value);
};

<MDBBtn onClick={() => this.getTextValue(1)}>1</MDBBtn>
getTextValue=(value)=>{
log(“getTextValue=>char:”,value);
};
this.getTextValue(1)}>1
您还可以对按钮使用循环:

const buttons = [1,2,3];

buttons.map(value => <MDBBtn onClick={() => this.getTextValue(value)}>{value}</MDBBtn>)
const按钮=[1,2,3];
buttons.map(value=>this.getTextValue(value)}>{value})

最简单的方法是使用箭头功能

<MDBBtn innerRef={this.btnRef1} onClick={()=>this.buttonClicked(1)}>
1
</MDBBtn>
this.buttonClicked(1)}>
1.
您只需在函数调用中传递要记录的值


此方法简单有效,但您可能需要注意一些性能问题。您可以在这里阅读它们:

最简单的方法是使用箭头函数

<MDBBtn innerRef={this.btnRef1} onClick={()=>this.buttonClicked(1)}>
1
</MDBBtn>
this.buttonClicked(1)}>
1.
您只需在函数调用中传递要记录的值

此方法简单有效,但您可能需要注意一些性能问题。你可以在这里阅读它们: