我想在React中单击按钮来更改状态。 本质上,我试图通过将this.state.name设置为等于文本框中键入的内容来更新div中显示的名称的值。
我在这里做什么错了?
我也不太了解onClick = {()=> this.updateText()}和onClick = {this.updateText()}和/或onClick = {this.updateText}之间的区别。也许与此有关吗?
Form.tsx
import React from 'react';
export default class Form extends React.Component<any, any> {
constructor(props: any) {
super(props);
this.state = {
title: "Enter a new name here",
description: "Hola",
textInput: null,
name: this.props.name
};
}
updateText() {
this.setState({
name: this.state.textInput
});
}
render() {
return (
<div className="App">
<div>{this.props.text} {this.state.name}</div>
<div>{this.state.age}</div>
<input type="text" placeholder={this.state.title}>{this.state.textInput}</input>
<br />
<button type="submit" onClick={() => this.updateText()}>Submit</button>
</div>
);
}
}
App.tsx
import React from 'react';
import './App.css';
import Form from "./Form";
class App extends React.Component {
render() {
return (
<div className="App">
<Form text="Hello" age={22} name="Thomas"/>
</div>
);
}
}
export default App;
在键入内容并单击提交按钮后,this.state.name会显示为空或空。
答案 0 :(得分:0)
正如@Alexander Staroselsky在他的评论中所说,您应该使用onChange
处理程序进行输入。这样,您可以更新textInput
并将其设置为name
值。
{this.updateText()}
不是使用处理程序的正确方法。如果您这样使用它,则会在每个渲染上调用它,但不会在单击时调用它。
onClick={this.updateText}
在这里,您可以使用函数引用,它可以工作。但是,您必须将其绑定到构造函数中或将其定义为箭头函数。您可以在下面看到一个示例。
onClick={() => this.updateText()}
这是使用它的一种选择。您在此处为处理程序使用箭头功能。它也无需绑定您的this
处理函数即可使用。但是,通过这种方式,您的处理程序函数将在每次渲染时重新创建。尽可能避免这种情况。
class App extends React.Component {
render() {
return (
<div className="App">
<Form text="Hello" age={22} name="Thomas"/>
</div>
);
}
}
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
title: "Enter a new name here",
description: "Hola",
textInput: "",
name: this.props.name
};
}
updateText = () => {
this.setState({
name: this.state.textInput
});
}
handleChange = (e) => this.setState({ textInput: e.target.value})
render() {
return (
<div className="App">
<div>{this.props.text} {this.state.name}</div>
<div>{this.state.age}</div>
<input value={this.state.textInput} onChange={this.handleChange} type="text" placeholder={this.state.title} />
<br />
<button type="submit" onClick={this.updateText}>Submit</button>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root" />