我想通過在我的app.js中執行onchange事件來更新標題組件的標題,但似乎無法正確地綁定它們。所以當用戶鍵入輸入時,它將顯示標題組件中的文本。React事件句柄OnChange
APP.JS
import React, { Component } from 'react';
import './App.css';
import Header from './Header';
class App extends Component {
constructor(props) {
super(props);
this.state = {name: "Michael"}
}
handleChange(e) {
const name = e.target.value;
this.changeTitle(name);
}
render() {
return (
<div className="App">
<Header changeTitle={this.changeTitle.bind(this)} title={this.state.name}/>
<p className="App-intro">
Type here to change name.
<input type="text" onChange={this.handleChange.bind(this)}/>
</p>
</div>
);
}
}
export default App;
HEADER.JS
import React, { Component } from 'react';
import logo from './logo.svg';
class Header extends Component {
changeTitle(name) {
this.setState({name});
}
render() {
return (
<div>
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React {this.props.name}</h2>
</div>
</div>
);
}
}
export default Header;
您需要在父組件設置狀態,然後通過標題爲道具,以頭組件。 –