父組件中通過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
