react-子組件與父組件

子組件改變父組件的state
class Parent extends Component{
state = {
msg: 'start'
};
render() {
return <Child_1 msg={this.state.msg} />;
}
}
class Child_1 extends Component{
render() {
return <p>{this.props.msg}</p>
}
}

父組件改變子組件的內(nèi)容
class Parent extends Component{
render() {
return <Child_1 inputPlaceholder="請輸入" />;
}
}
class Child_1 extends Component{
render() {
const { inputPlaceholder } = this.props;
return <input placeholder={inputPlaceholder} />
}
}

父組件調(diào)用子組件的方法
方法一:
import React, {Component} from 'react';
export default class Parent extends Component {
render() {
return(
<div>
<Child onRef={this.onRef} />
<button onClick={this.click} >click</button>
</div>
)
}
onRef = (ref) => {
this.child = ref
}
click = (e) => {
this.child.myName()
}
}
class Child extends Component {
componentDidMount(){
this.props.onRef(this)
}
myName = () => alert('xiaohesong')
render() {
return ('wo')
}
}
方法二:
import React, {Component} from 'react';
export default class Parent extends Component {
click = () => {
this.divRef.myName();
}
render() {
return(
<div ref={refs => this.divRef =refs}> />
)
}
}
class Child extends Component {
myName = () => alert('xiaohesong')
}

子組件調(diào)用父組件的方法
class Parent extends Component{
onChange = (value) => {
...
}
}
class Child extends Component{
this.props.onChange(value);
}

父組件引用多個相同子組件,分別向該子組件傳值的方法
class Parent extends Component{
onChange = (value) => {
...
}
render() {
return (
<div>
<Child showStatus={0} />
<Child showStatus={1} />
</div>
)
}
}
class Child extends Component{
componentDidMount() {
const showStatus = this.props.showStatus;
if (showStatus === 0) {
} else if (showStatus === 1) {
}
}
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容