1. 父子相互傳值函數(shù)方法
1.父組件
import React, { useState,useEffect } from 'react'
import { Link, withRouter } from 'react-router-dom'
import Child from './child4';
import { Result, Button } from 'antd'
const NoEorr = () => {
const state = {
msg:'我是父組件的信息' //1.父組件準(zhǔn)備數(shù)據(jù)
}
const [myname, setMyname] = useState("冠軍侯")
function getChidMsg(childVal){
setMyname(childVal)
console.log(childVal)
}
return (
<>
<Child pMsg={state.msg} getMsc={getChidMsg}></Child>
<div>
<Button type="primary">{myname}</Button>
</div>
</>
)
}
export default NoEorr
2.子組件
import React from 'react'
import { Link } from 'react-router-dom'
import { Result, Button } from 'antd'
const Sonny = (prop) => {
console.log(prop)
const {pMsg} = prop
function handClick(){
console.log(prop)
prop.getMsc("我從子組件來(lái)")
}
return (
<>
<Button type="primary" onClick={handClick}>這個(gè)是子組件</Button>
<Button type="primary">{pMsg}</Button>
</>
)
}
export default Sonny
2滑潘,還有一種父子相互傳值的
1.父組件
import React, { Component } from 'react'
import Son from './child4'
export default class Father extends Component {
constructor() {
super()
this.state = {
message: 'hello',
sonVal: null
}
}
render() {
return (
<div className="father-ri" id="father">
<h1>Father組件</h1>
<button onClick={() => { this.setState({ message: 'world' }) }} > 修改 </button>
<p>選擇了那種水果:{this.state.sonVal}</p>
<Son data={this.state.message} handle={this.testAction.bind(this)} />
</div>
)
}
// 接收子組件數(shù)據(jù)
testAction(value) {
console.log(this)
console.log(value)
this.setState({ sonVal: value })
}
}
2.子組件
import React, { Component } from 'react'
export default class Son extends Component {
constructor() {
super()
this.state = {
select: '蘋果'
}
}
render() {
let arr = ['蘋果', '香蕉', '西瓜']
return (
<div className="child-ri" id="son">
<h1>Son組件</h1>
<p>接收到的值為:{this.props.data}</p>
{arr.map((item, index) => {
return (
<p key={index}>
{item}:
<input
type="radio"
value={item}
checked={this.state.select == item}
onChange={this.inputChange.bind(this)}
/>
</p>
)
})}
</div>
)
}
inputChange(ev) {
let value = ev.target.value
this.setState({ select: value })
// 調(diào)用父組件的方法语卤,將值傳遞給父組件
this.props.handle(value)
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者