父組件js
import React, { Component } from 'react'; import Son from './Son' import './Father.css' class Father extends Component { constructor(props) { super(props); this.state = { inputVal: '', tmp: '' } } render() { let value = 4131783; let {inputVal} = this.state; return ( <div className="father"> <h1>我是父組件</h1> <input type="text" value={inputVal} onChange={this.inputChangeAction}/> <button onClick={this.sendAction}>發送</button> <Son title="hello react" val={value} inputValue={this.state.tmp}/> </div> ); } inputChangeAction = (ev)=>{ this.setState({inputVal: ev.target.value}); } sendAction = ()=>{ //輸入框的值 this.state.inputVal this.setState({tmp: this.state.inputVal}); } } export default Father;
父組件css
.father{
padding: 50px;
background: lemonchiffon;
}
子組件js
import React, { Component } from 'react'; import './Son.css' class Son extends Component { // this.props.xxx 外部調用組件時,傳入組件的屬性,只能使用,不能修改。數據單向自頂向下傳遞的 // this.state.xxx 內部的狀態,內部狀態可以使用也可以修改 render() { console.log(this.props.title); return ( <div className="son"> <h1>我是子組件</h1> <p>接收到的title值為:{this.props.title}</p> <p>接收到的val值為:{this.props.val}</p> <p>接收到的inputValue值為:{this.props.inputValue}</p> </div> ); } } export default Son;
子組件css
.son{
padding: 30px;
background: lightblue;
}