React子组件继承问题:父组件变量无法传递给子组件
React父子组件传值问题的修复方案
你的代码存在几个关键问题:
- props是只读的,不能直接修改:React规定组件不能修改传入的props,
props.foo = name这种写法不符合React的设计原则,也不会生效。 - 函数组件不能用
this.props:App是函数组件,不存在this对象,<Child foo={this.props} />里的this是undefined,而且这种写法也无法获取到Parent里的name值。 - 已创建的React元素不可变:Parent返回的
props.children是已经生成的Child元素,直接修改它的props不会触发更新,因为React元素是不可变对象。
方案一:Render Props模式(适合简单父子传值)
让Parent通过函数形式传递子组件,把需要共享的值作为参数传给函数,子组件就能拿到该值:
function Parent(props) { const name = 'Jimmy'; // 调用子组件函数,传递name值 return props.children(name); } function Child(props) { return <h1>hello, {props.foo}</h1> } export default function App() { return ( <div className="App"> <Parent> {/* 用函数接收Parent传来的name,再传给Child */} {(name) => <Child foo={name} />} </Parent> </div> ); }
方案二:Context API(适合多层组件共享值)
如果后续有更多层级的组件需要使用这个值,用Context更方便:
import React from 'react'; // 创建Context对象 const NameContext = React.createContext(); function Parent(props) { const name = 'Jimmy'; return ( <NameContext.Provider value={name}> {props.children} </NameContext.Provider> ); } function Child() { // 通过useContext获取Context中的值 const name = React.useContext(NameContext); return <h1>hello, {name}</h1> } export default function App() { return ( <div className="App"> <Parent> <Child /> </Parent> </div> ); }
内容的提问来源于stack exchange,提问作者James Koponen
相关产品推荐
相关产品推荐

