react函数组件的父子传值

1.父向子传值
父组件data={data} ,子组件props.data

const Child = (props) => {
    return (
      
{props.name}{props.data}
); }; const Father = () => { const [data, setData] = useState('ikun'); return (
); };

2.子向父传值

【总之儿子向父亲传值就是,父亲传一个函数给儿子,在儿子那里执行这个函数,导致父亲的某个值有了新的变化】

子组件写handlerChange方法,handlerChange={handlerChange}

父组件接收props.handlerChange(val)

const Child = (props) => {
    const [value, setValue] = useState(undefined);
    return (
      
props.handlerChange(e.target.value)} className="input" />
); }; const App = () => { const [data, setData] = useState(''); const handlerChange = (text) =>{ setData(text) } return (

{data}

); };

3父组件调用子组件的函数【方法】

const ChildInput = forwardRef((props,ref) => {
  const { label } = props
  const [value,setValue] = useState('')
  //这里写所有暴露的方法和值
  useImperativeHandle(ref, () => ({
    getValue
}))
  const handlerChange = (e) =>{
    const value = e.target.value
    setValue(value)
  }
  const getValue = useCallback(() => {
    return value
  },[value])
  return (
    
{label}:
); }); const App = (props) => { const inputEl = useRef(null) const [node,setNode] = useState('') const handleFocus = () => { setNode(inputEl.current.getValue()) } return (

{node}

); };

你可能感兴趣的:(reactjs)