gpt4 book ai didi

javascript - React Component 没有在 setState 上重新渲染

转载 作者:行者123 更新时间:2023-11-28 16:16:56 26 4
gpt4 key购买 nike

我有以下代码。我正在使用 setState 方法设置状态 (this.setState({ country: "", offset: ""});) 并且它不会导致 render() 方法重新渲染通过它自己。

  state = { country: "", offset: "" };
onClicked = () => {
console.log("Fine Click away");
// Get the call back from props
let country = this.state.country;
let offset = this.state.offset;
this.setState({ country: "", offset: "" });
const callback = this.props.onpress;

if (callback) {
callback(country, offset);
}
};
getTheCountryName = event => {
this.setState({ country: event.target.value });
};
getTheOffSet = e => {
this.setState({ offset: e.target.value });
};
render() {

const Caption = this.props.caption;
return (
<div>
<br></br>
<br></br>
<div>Please enter the name of country and offset:</div>
<input
placeholder="Name of Country"
onChange={this.getTheCountryName}
/>
<input placeholder="offset" onChange={this.getTheOffSet} />
<br></br>
<br></br>
<button className="rectangular-button" onClick={this.onClicked}>
<div className="caption">{Caption}</div>
</button>
</div>
);
}
}```

最佳答案

以任何方式重置状态都不会触发输入值的更新,因为您实际上并没有在要返回的 JSX 中使用您的状态。下面的代码会将值提供给输入,以便在您的状态更改时更新它们。您可以在 React 中阅读有关表单和受控输入的信息 here :

class App extends React.Component {
state = { country: "", offset: "" };
onClicked = () => {
console.log("Fine Click away");
// Get the call back from props
let country = this.state.country;
let offset = this.state.offset;
this.setState({ country: "", offset: "" });
const callback = this.props.onpress;

if (callback) {
callback(country, offset);
}
};
getTheCountryName = event => {
this.setState({ country: event.target.value });
};
getTheOffSet = e => {
this.setState({ offset: e.target.value });
};
render() {

const Caption = this.props.caption;
return (
<div>
<br></br>
<br></br>
<div>Please enter the name of country and offset:</div>
<input
placeholder="Name of Country"
onChange={this.getTheCountryName}
value={this.state.country}
/>
<input value={this.state.offset} placeholder="offset" onChange={this.getTheOffSet} />
<br></br>
<br></br>
<button className="rectangular-button" onClick={this.onClicked}>
<div className="caption">Reset</div>
</button>
</div>
);
}
}

关于javascript - React Component 没有在 setState 上重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58052079/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com