在react中的事件处理程序中使用子组件props值



这是我的代码

import React from 'react';
import './style.scss';
const CalcButton = (props) => {
return (
<button id="calcBtn" style={props.style} onClick={props.onClick}>
{props.btnText}
</button>
);
};
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
currentNum: '0',
log: ' ',
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
console.log('a', e.target.value);
this.setState((state) => ({
currentNum: state.currentNum + e.target.getAttribute(this.props.btnText),
}));
}
render() {
return (
<div id="container">
<div id="display">
<h3 id="log">{this.state.log}</h3>
<h3 id="currentNum">{this.state.currentNum}</h3>
</div>
<CalcButton
style={{
width: 150,
backgroundColor: 'rgb(173, 0, 0)',
}}
btnText="AC"
onClick={() => {
return this.setState({
currentNum: '',
log: '',
});
}}
/>
<CalcButton
btnText="/"
style={{
backgroundColor: 'gray',
}}
/>
<CalcButton
btnText="X"
style={{
backgroundColor: 'gray',
}}
/>
<CalcButton btnText="7" onClick={this.handleClick}/>
<CalcButton btnText="8" />
<CalcButton btnText="9" />
<CalcButton
btnText="-"
style={{
backgroundColor: 'gray',
}}
/>
<CalcButton btnText="4" />
<CalcButton btnText="5" />
<CalcButton btnText="6" />
<CalcButton
btnText="+"
style={{
backgroundColor: 'gray',
}}
/>
<CalcButton btnText="1" />
<CalcButton btnText="2" />
<CalcButton btnText="3" />
<CalcButton
btnText="="
style={{
float: 'right',
height: 150,
backgroundColor: 'rgb(34, 86, 134)',
}}
/>
<CalcButton
btnText="0"
style={{
width: 150,
}}
/>
<CalcButton btnText="." />
</div>
);
}
}
export default App;

正如你所看到的,我正在尝试构建一个计算器,但我面临的问题是,我想在handleClick事件处理程序中使用CalcButton的btnText prop值,但我不知道如何在所述事件处理程序中将其访问。我知道这是一个非常基本的问题,但相信我,我已经搜索过了,找不到任何关于我的问题的参考资料,请帮忙。

将数据btntext={props.btntext}添加到CalcButton函数中的按钮元素。然后使用e.target.dataset.btntext访问它。–Emil Karlsson

上面提到的评论解决了这个问题,尽管我确实同意@maxagno3的回答,但是,由于我还在学习,我真的很想学习这个概念。

谢谢你的回答。

我认为您不需要创建CalcButton组件。由于您的按钮文本将是相同的,您可以通过以下方式进行操作-

  • 创建一个新状态,将按钮文本存储在数组中
  • 映射该状态并为计算器创建按钮
  • 使用句柄单击功能时,请传入按钮文本值
  • 在该功能中,检查按钮文本是否为AC,然后执行另一个功能或设置状态值。最好为AC按钮创建一个单独的函数,并在handleClick函数内的if-else条件中调用它

如果你真的需要创建组件,那么你需要将句柄点击函数添加到你正在重用的多个组件中,并将按钮文本的值作为参数传入其中。

我希望这能有所帮助。

在子组件中:

const CalcButton = (props) => {
const handleClick = () => {
if (props.onClick) {
props.onClick(props.btnText);
}
};
return (
<button id="calcBtn" style={props.style} onClick={handleClick}>
{props.btnText}
</button>
);
};

在父组件中:

class App extends React.Component { ...
handleClick(val) {
console.log('a', val);
this.setState((state) => ({
currentNum: state.currentNum + val,
}));
}
......
<CalcButton btnText="7" onClick={this.handleClick}/>

最新更新