[英]How to make buttons act as radio buttons in React.js by changing states?
我對 React 還很陌生,想嘗試制作一個尋路可視化工具。 我希望有可以單擊的按鈕,這將使特定的尋路算法處於活動狀態,而其他所有算法都處於非活動狀態,但我無法實現這一點。
我有一個呈現按鈕的選項組件:
export class Options extends React.Component {
constructor(props) {
super(props);
this.state = {
dijkstra: false,
aStar: false,
bestSearch: false,
bfs: false,
dfs: false,
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(name) {
this.setState({
dijkstra: false,
aStar: false,
bestSearch: false,
bfs: false,
dfs: false,
});
this.setState({ [name]: true });
}
render() {
return (
<div className='toolbar'>
<div className='algorithms'>
<Button
name="Dijkstra's Algorithm"
type='dijkstra'
isActive={this.state.dijkstra}
onClick={this.handleClick}
/>
<Button
name='A* Algorithm'
type='aStar'
isActive={this.state.aStar}
onClick={this.handleClick}
/>
<Button
name='Best First Search'
type='bestSearch'
isActive={this.state.bestSearch}
onClick={this.handleClick}
/>
<Button
name='BFS'
type='bfs'
isActive={this.state.bfs}
onClick={this.handleClick}
/>
<Button
name='DFS'
type='dfs'
isActive={this.state.dfs}
onClick={this.handleClick}
/>
</div>
<div className='info'></div>
<div className='legend'></div>
</div>
);
}
}
state 用於跟蹤哪個算法處於活動狀態,而 handleClick 根據按鈕的鍵更改 state。 以下是 Button 組件的代碼:
export class Button extends React.Component {
constructor(props) {
super(props);
this.state = {
isActive: false,
};
}
componentWillReceiveProps() {
if (this.props.isActive) this.setState({ isActive: true });
}
render() {
let active = "";
if (this.state.isActive) {
active = "active";
}
return (
<button
className={`button ${active}`}
onClick={this.props.onClick(this.props.type)}
>
{this.props.name}
</button>
);
}
}
我收到錯誤消息“超出最大更新深度。當組件在 componentWillUpdate 或 componentDidUpdate 中重復調用 setState 時,可能會發生這種情況。React 限制嵌套更新的數量以防止無限循環。”
有什么幫助我可以糾正這個或更好的方法來實現這個嗎?
當你這樣做時:
<button
className={`button ${active}`}
onClick={this.props.onClick(this.props.type)}
>
它將onClick
設置為this.props.onClick(this.props.type)
返回的任何內容。 所以每次渲染時,它都會調用this.props.onClick
,這會調用setState
,這會導致重新渲染,它會再次調用它,等等。
你可能想做:
onClick={() => this.props.onClick(this.props.type)}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.