我有一个组件UserInput及其在App组件中使用(基于类。)现在,我无法在html中呈现onChange事件
import React from 'react';
const userInput =(props) =>{
return(
<input onChange={props.changed} />
);
};
export default userInput;
我的应用程序组件看起来像这样。
import React, { Component } from 'react';
import './App.css';
import UserInput from './UserInput/UserInput';
import UserOutput from './UserOutput/UserOutput';
class App extends Component{
constructor(props) {
super(props);
this.state = { userName: "dssdf" };
this.handleChange = this.handleChange.bind(this);
}
const handleChange = (event) =>{
this.setState({
userName: event.target.value
})
}
render(){
return(
<div >
<UserInput changed={this.handleChange} />
<UserOutput userName={this.state.userName} />
</div>
)
}
}
export default App;
需要任何帮助。
谢谢
答案 0 :(得分:1)
将状态作为值传递给<input />
import React from 'react';
const userInput =(props) =>{
return(
<input value={props.value} onChange={props.changed} />
);
};
export default userInput;
class App extends Component{
constructor(props) {
super(props);
this.state = { userName: "dssdf" };
this.handleChange = this.handleChange.bind(this);
}
const handleChange = (event) =>{
this.setState({
userName: event.target.value
})
}
render(){
return(
<div >
<UserInput value={this.state.userName} changed={this.handleChange} />
<UserOutput userName={this.state.userName} />
</div>
)
}
}