react父组件调用子组件方法

react

父组件中通过react.CreateRef()声明一个ref,将声明的变量绑定到标签的ref中,那么该变量的current则指向绑定的标签dom。

父组件

import React, { useState } from 'react';

import List from "./../List/index.jsx"

function Home (){

const billPictureRef = React.createRef();

const [list, setList] = useState([{

id:'1',

name:'葡萄'

},{

id:'2',

name:'西红柿'

}]);

const fn =()=>{

billPictureRef.current.handClick()

}

return (

<div onClick={fn}>

<List list={list} ref={billPictureRef}/>

</div>

)

}

export default Home

子组件

import React from 'react';

class List extends React.Component {

constructor(props){

super(props);

this.state = {}

}

handClick=()=>{

console.log(1);

}

render(){

const { list } = this.props

return (

<ul>

{

list && list.map(item=>{

return <li key={item.id} >{item.name}</li>

})

}

</ul>

)

}

}

export default List

 

 

 

以上是 react父组件调用子组件方法 的全部内容, 来源链接: utcz.com/z/384018.html

回到顶部