反应:如何将数据传递给孩子

时间:2020-11-02 09:46:55

标签: javascript reactjs

我是React的初学者,我做的可能没有意义。
我想做的只是将数据从父组件传递到每个屏幕中使用的父组件中。

我的代码是这样的。

AppDrawer.tsx

const AppDrawer: React: FC<Props> = ({
    children,
  }) => {
    const [aString, setString] = React.useState<string>('Hello');
...

<div>
  <Drawer>
    ...
  </Drawer/>
  <main>
    <div>
      <Container>
        {children}
      </Container>
    </div>
  </main>
</div>

App.tsx

<Swith>
    <AppDrawer>
        <Route path="/" component={ChildCompoent} />
        ...
        ...
    </AppDrawer>
</Switch>

ChildComponent.tsx

export default class ChildComponent extends React.Component<Props, State> {
  state = {
    ..
  }
}

现在我想在子组件的aString中访问AppDrawer.tsx,但是我不知道该怎么做。我该怎么办?

3 个答案:

答案 0 :(得分:2)

我认为您可以在此处使用Context。上下文允许您从父组件中传递某些内容,并且可以根据需要在子组件处获取它(无论它有多深)。

我举了一个例子link

您可以详细了解here

已更新:我注意到您使用的是Route,Router,并且在我的codeandbox中没有使用。但是,这很好。主要思想是使用上下文:D

答案 1 :(得分:1)

在组件Route中使用渲染

<Route
  path='/'
  render={(props) => (
    <ChildCompoent {...props}/>
  )}
/>

并且不应在组件AppDrawer中支持aString

答案 2 :(得分:0)

我不确定react的版本以及是否仍受支持,但这不是我在应用程序中的操作方式。 尝试检查React。这里的孩子:https://reactjs.org/docs/react-api.html#reactchildren 看看是否适合您的情况。

    render() {
        const children = React.Children.map(this.props.children, child => {
            return React.cloneElement(child, {
                ...child.props,
                setHasChangesBeenMade: (nextValue) => this.setState({ hasChangesBeenMade: nextValue })
            });
        });

        return (children[0]);
    }

对您来说应该是这样的:

const AppDrawer: React: FC<Props> = ({
    children,
  }) => {
    const [aString, setString] = React.useState<string>('Hello');
...

        const childrens = React.Children.map(children, child => {
            return React.cloneElement(child, {
                ...child.props,
                aString: aString
            });
        });
<div>
  <Drawer>
    ...
  </Drawer/>
  <main>
    <div>
      <Container>
        {childrens[0]}
      </Container>
    </div>
  </main>
</div>