使用 setState() 反应输入元素的 onChange 不起作用
React input element's onChange using setState() doesn't work
我想制作一个应用程序,以便当在输入元素中键入文本时,这将反映输出中的变化。到目前为止,更新不起作用:(
import React, { Component } from 'react';
import './App.css';
import UserInput from './UserInput/UserInput';
import UserOutput from './UserOutput/UserOutput';
class App extends Component {
state = {
user: [
{ username: 'Kai' },
{ username: 'Orange' }
]
}
inputChangeHandler = (e) => {
this.setState(
{
user: [
{ username: e.target.value },
{ username: e.target.value }
]
}
)
}
render() {
return (
<div className="App">
<UserInput onChange={this.inputChangeHandler} />
<UserOutput username={this.state.user[0].username} />
<UserOutput username={this.state.user[1].username} />
</div>
);
}
}
export default App;
input 元素中键入的文本更改应反映为 UserOutput 中呈现的用户名。这行不通。
这是其他组件的代码...
import React, { Component } from 'react';
class UserInput extends Component
{
render() {
return(
<div>
<input />
</div>
);
}
}
export default UserInput;
和
import React, { Component } from 'react';
class UserOutput extends Component
{
render() {
return(
<div>
<p>First paragraph and my name is {this.props.username}</p>
<p>Second paragraph </p>
</div>
);
}
}
export default UserOutput;
好的,这是你的问题。您没有将更改处理程序分配给 UserInput
组件中的输入元素。应该是:
<input onChange={this.props.onChange} />
我想制作一个应用程序,以便当在输入元素中键入文本时,这将反映输出中的变化。到目前为止,更新不起作用:(
import React, { Component } from 'react';
import './App.css';
import UserInput from './UserInput/UserInput';
import UserOutput from './UserOutput/UserOutput';
class App extends Component {
state = {
user: [
{ username: 'Kai' },
{ username: 'Orange' }
]
}
inputChangeHandler = (e) => {
this.setState(
{
user: [
{ username: e.target.value },
{ username: e.target.value }
]
}
)
}
render() {
return (
<div className="App">
<UserInput onChange={this.inputChangeHandler} />
<UserOutput username={this.state.user[0].username} />
<UserOutput username={this.state.user[1].username} />
</div>
);
}
}
export default App;
input 元素中键入的文本更改应反映为 UserOutput 中呈现的用户名。这行不通。
这是其他组件的代码...
import React, { Component } from 'react';
class UserInput extends Component
{
render() {
return(
<div>
<input />
</div>
);
}
}
export default UserInput;
和
import React, { Component } from 'react';
class UserOutput extends Component
{
render() {
return(
<div>
<p>First paragraph and my name is {this.props.username}</p>
<p>Second paragraph </p>
</div>
);
}
}
export default UserOutput;
好的,这是你的问题。您没有将更改处理程序分配给 UserInput
组件中的输入元素。应该是:
<input onChange={this.props.onChange} />