我在render()
中有一个按钮,我希望它onClick()
设置状态。我知道你不应该在render()
中设置状态,因为它会导致无限循环,所以我应该怎么做呢?
function initialState(props) {
return {
edit: false,
value: props.value,
};
}
export default class MyButton extends React.Component {
constructor(props) {
super(props);
this.state = initialState(props);
}
onCancel() {
this.setState({ edit: false, value: this.props.value });
}
onClick() {
this.state.edit ? this.onCancel() : this.setState({ edit: true });
}
render() {
return (
<div onClick={this.onClick}>
BUTTON
</div>
);
}
更新以显示我现在正在尝试的代码以及我收到数千次的警告:
Warning: setState(...): Cannot update during an existing state transition (such as
within `render` or another component's constructor). Render methods should be a
pure function of props and state; constructor side-effects are an anti-pattern, but
can be moved to `componentWillMount`.
warning @ warning.js?0260:44
getInternalInstanceReadyForUpdate @ ReactUpdateQueue.js?fd2c:51
enqueueSetState @ ReactUpdateQueue.js?fd2c:192
ReactComponent.setState @ ReactComponent.js?702a:67
onCancel @ mybutton.js?9f63:94
onClick @ mybutton.js?9f63:98
render @ mybutton.js?
...
答案 0 :(得分:0)
要为您的用例设置状态,您需要在某处设置状态,但我不会这样做。我会将一个函数绑定到onClick
事件。
function initialState(props) {
return {
edit: false,
value: props.value,
};
}
export default class MyButton extends React.Component {
constructor(props) {
super(props);
this.state = initialState(props);
this.handleButtonClick = this.onClick.bind(this);
}
onCancel() {
this.setState({ edit: false, value: this.props.value });
}
onClick() {
this.state.edit ? this.onCancel() : this.setState({ edit: true });
}
render() {
return (
<div onClick={this.handleButtonClick}>
BUTTON
</div>
);
}
查看here了解更多信息
答案 1 :(得分:0)
由于之前的答案没有解决问题,因此不确定您要做什么。因此,如果您提供更多信息,可能会更容易。
但这是我的看法:
getInitialState() {
return (
edit: true
);
}
handleEdit() {
this.setState({edit: true});
}
handelCancel() {
this.setState({edit: false});
}
render() {
var button = <button onClick={this.handelEdit}>Edit</button>
if(this.state.edit === true) {
button = <button onClick={this.handelCancel}>Cancel</button>
}
return (
<div>
{button}
</div>
);
}
答案 2 :(得分:0)
尝试使用箭头函数将onBtnClick
和onCancel
函数绑定到上下文,看看它是否能解决您的问题。
function initialState(props) {
return {
edit: false,
value: props.value,
};
}
export default class MyButton extends React.Component {
constructor(props) {
super(props);
this.state = initialState(props);
}
onCancel = ()=> {
this.setState({ edit: false, value: this.props.value });
}
onBtnClick = () => {
this.state.edit ? this.onCancel() : this.setState({ edit: true });
}
render() {
return (
<div onClick={this.onBtnClick}>
BUTTON
</div>
);
}