【发布时间】:2019-03-15 23:35:42
【问题描述】:
按钮组件(子)
export default class Button extends React.Component {
render() {
var handleToUpdate = this.props.handleToUpdate;
return (
<button onClick={() => handleToUpdate(this.id)}>
{this.props.title}
</button>
);
}
}
索引(父)
作为回报
<Button title={title1} handleToUpdate={handleToUpdate.bind(this)} />
<Button title={title2} handleToUpdate={handleToUpdate1.bind(this)} />
<Button title={title3} />
<Button title={title4} />
在渲染中
const title1 = "test1"
const title2 = "test2"
const title3 = "test3"
const title4 = "test4"
var handleToUpdate = this.handleToUpdate;
var handleToUpdate1 = this.handleToUpdate1;
功能
handleToUpdate() {
this.setState({})
}
handleToUpdate1() {
this.setState({})
}
var handleToUpdate = this.handleToUpdate.bind(this);
var handleToUpdate1 = this.handleToUpdate1.bind(this);
我的代码没有问题,但我认为我处理该函数的方式不是好的做法。
我在这里做的是我制作了按钮组件(子)并在父(索引)中调用它四次。我创建了onClick props 来调用函数,然后设置状态。
是否有任何替代方法可以使用 4 setState 创建一个函数并根据单击的按钮 ID 调用状态。
为了更清楚。
单击按钮 1 => 调用 singlefunction => setstate1
单击按钮 2 => cal singlefunction => setstate 2 ...
【问题讨论】:
-
可以将按钮点击事件传递给handToUpdate函数,然后通过switch语句判断哪个按钮被点击,然后设置相应的状态?
-
@AshleyBrown 能否提供一段代码或相同的示例。请
-
完成,看看我的答案。
-
id保存在哪里? -
将其存储在单个按钮上?我以为你已经设置好了,因为你通过了
(this.id)
标签: javascript reactjs