首页 > 解决方案 > 如何将变量传递给道具中收到的组件?

问题描述

在 Layout.jsx 中,我有以下结构,其中 children 是一个组件。

如何将“名称”传递给“孩子”组件?

const Home = () => {
    return <h1>Hello world!</h1>; {/* here I need the name */}
};

class App extends Component {
    render() {
        return (
        <Layout>
            <Switch>
                <Route path='/' component={Home}/>
                ...
            </Switch>
        </Layout>
        );
    }
}

class Layout extends Component {
    name = "John";
    render() {
        const { children } = this.props;
        return (
        <div>
            { children }
        </div>
        );
    }
}

标签: reactjsjsxreact-props

解决方案


React 组件必须是大写的。如果child变量包含一个 React 组件,您可以将其存储在某个大写变量中,然后作为标签呈现。

const { child: Child } = this.props;

return (
  <div>
    <Child name={this.name} />
  </div>
);

推荐阅读