react組件傳值的四種方法
1、父向子傳值
父組件
classAppextendsReact.Component{
state={
name:'jack',
age:19,
gender:'男',
count:1
}
render() {
return<div >
御劍乘風(fēng)來,除魔天地間!
<Child {...this.state} hobby={[1,2,3,4]}></Child>
</div>
}子組件:
const Child = (props) => {
console.log(props,99);
return<div>
御劍乘風(fēng)來,除魔天地間!===Child======{props.count}
</div>
};2、子向父傳值
父組件
classAppextendsReact.Component{
state={
name:'jack',
age:19,
gender:'男',
count:1
}
handle2=(msg)=>{
console.log(msg,77); // 123
}
render() {
return<div >
御劍乘風(fēng)來,除魔天地間!==
<ChildgetMsg={this.handle2}></Child>
</div>
}子組件:
const Child = (props) => {
console.log(props,99);
var handle=()=>{
console.log(111);
props.getMsg('123')
}
return<div>
御劍乘風(fēng)來,除魔天地間!===Child======
<buttononClick={handle}>child1</button></div>
};3、非父子傳值
child1 向 child2 傳值
思路:child 傳到app ,然后app傳到child2
classAppextendsReact.Component{
state={
name:'jack',
age:19,
gender:'男',
count:1
}
handle2=(msg)=>{
console.log(msg,77); // 123this.setState({
count:this.state.count+msg
})
}
render() {
return<div >
御劍乘風(fēng)來,除魔天地間!==
<ChildgetMsg={this.handle2} ></Child>
<Child2count={this.state.count}></Child2>
</div>
}子組件1:
const Child = (props) => {
console.log(props,99);
var handle=()=>{
console.log(111);
props.getMsg('123')
}
return<div>
御劍乘風(fēng)來,除魔天地間!===Child======
<buttononClick={handle}>child1</button></div>
};
const Child2 = (props) => {
console.log(props,99);
var handle=()=>{
console.log(111);
props.getMsg('123')
}
return<div>
御劍乘風(fēng)來,除魔天地間!===Child======
<buttononClick={handle}>child1</button></div>
};4、Context 方法 傳值 【類似vue的 provide / inject】
步驟:
1- const {Provider,Consumer} = React.createContext()
2- Provider包裹父組件 定義value是需要傳的值 ====<Provider value={this.state.count}>
3- Consumer包裹需要接收數(shù)據(jù)的組件 data接收數(shù)據(jù)
<Consumer >
{data=>(
<div>
御劍乘風(fēng)來,除魔天地間! ==Child2*****{data}
</div>
)}代碼如下:
import React from 'react'const {Provider,Consumer} = React.createContext()
const Child = (props) => {
console.log(props,99);
return <div>
御劍乘風(fēng)來,除魔天地間!===Child
</div>
};
classChild2extendsReact.Component{
render() {
return <div>
<Consumer >
{data=>(
<div>
御劍乘風(fēng)來,除魔天地間! ==Child2*****{data}
</div>
)}
</Consumer>
</div>
}
}
classAppextendsReact.Component{
state={
name:'jack',
age:19,
gender:'男',
count:1
}
render() {
return <Provider value={this.state.count}>
御劍乘風(fēng)來,除魔天地間!=={this.state.name}
<Child></Child>
<Child2></Child2>
</Provider>
}
}
export default App到此這篇關(guān)于react組件傳值的四種方法的文章就介紹到這了,更多相關(guān)react組件傳值內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
手挽手帶你學(xué)React之React-router4.x的使用
這篇文章主要介紹了手挽手帶你學(xué)React之React-router4.x的使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-02-02
React-Native之TextInput組件的設(shè)置以及如何獲取輸入框的內(nèi)容
這篇文章主要介紹了React-Native之TextInput組件的設(shè)置以及如何獲取輸入框的內(nèi)容問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05

