React 父子组件之间传值,以及父组件如何获取子组件数据和方法

一.父组件如何获取子组件数据

0.类组件: 相关文章可以搜下,百度搜 react cref

重点说下函数组件

1.函数组件:

在函数组件中要获取子组件的数据,需要两步骤
1.将ref传递到子组件中,
2.需要使用forwardRef对子组件进行包装

1.父组件:

export default () => {
  const parentRef = useRef();
  function focusHander() {
    console.log(parentRef);
    parentRef.current.focus();
    parentRef.current.value = '哈哈';
  }
  return (
    <>
      <ForwardChild ref={parentRef} />
      <button onClick={focusHander}>获取焦点</button>
    </>
  )
}

2.子组件:

function Child(props, parentRef) {
  console.log(props);
  return (
    <>
      <input type="text" ref={parentRef} />
    </>
  )
}
/**
 * 使用forwardRef将ref直接传递进去
 */
let ForwardChild = forwardRef(Child);
export default ForwardChild;

2. 优化(使用 useImperativeHandle)

上面的方式都会将组件中全部的数据暴露出去,有时候我们想只想暴露出一部分数据
或者我们有时想把state里的数据暴露部分出去

1.父组件:

export default () => {
  const parentRef = useRef();

  const focusHandler = () => {
    parentRef.current.focus();
    console.log(parentRef)
  }
  return (
    <>
      <ForwardChidl ref={parentRef} name={'你好'} />
      <button onClick={focusHandler}>获取焦点</button>
    </>
  )
}

2.子组件:

import React, { useState, useRef, useImperativeHandle, forwardRef } from 'react'

function Child(props, parentRef) {
	const [data, setData] = useState([
		{	name: 'agag', age: 88},
		{	name: 'bb', age: 77},
		{	name: 'cc', age: 66},
	])
	const inputRef = useRef();
	useImperativeHandle(parentRef, () => {
	  // return返回的值就可以被父组件获取到,没返回的值就获取不到
	  return {
	    focus() {
	      inputRef.current.focus();
	    }dataobj:data
	  }
	})
	const handleChange = () => {
		setData([
			...data,
			{	name: 'ss', age: 99887},
		])
	}
	
  return (
    <>
      <p>{props.name}</p>
      <input type="text" ref={inputRef} />
      <button onClick={handleChange}>改变son的值</button>
    </>
  )
}

let ForwardChidl = forwardRef(Child);
export default ForwardChild;

相关文章:
https://segmentfault.com/a/1190000041639103/
https://juejin.cn/post/7024786617105645581
https://www.cnblogs.com/xiao-yaolx/p/15693405.html
https://blog.51cto.com/u_3409716/2904219

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值