如何从功能组件获取数据?

时间:2020-10-27 04:35:44

标签: react-native react-hooks

我有一个功能组件(A)导入另一个功能组件(B)。

B有一个onChange值,我想在将B导入A时一直获取onChange值。

我不知道如何获得它。

这是这样的代码:

A:

import B from './B';

const A = () => {
  // I want to get B's onChange value over here
  return (
    <B />
  );
}

B:

import React, { useState } from 'react';

const B = () => {
  const [value, setValue] = useState('');

  return (
    <SomePicker value={value} onChange={(value) => setValue(value)}
  );
} 

1 个答案:

答案 0 :(得分:1)

您可以参考以下解决方案。

import B from './B';

const A = () => {
 const getOnChangeValueFromB = (data) => {
   console.log(data)// you will get onChange value here
  };   
  // I want to get B's onChange value over here
  return (
    <B callBack={getOnChangeValueFromB}/>
  );
}

import React, { useState } from 'react';

const B = (props) => {
  const [value, setValue] = useState('');
const returnValueToA = (value) => {
    setValue(value)
    props.callBack(value);

  }
  return (
    <SomePicker value={value} onChange={(value) => returnValueToA(value)}
  );
}