繁体   English   中英

React:子组件中的父组件道具无需显式传递

[英]React: parent component props in child without passing explicitly

是否可以让父组件的 props 在子组件中可用而不传递它们。

我正在尝试实现一个提供者模式,以便访问其子组件中的所有提供者道具。 前任:

假设下面的提供者 comp FetchProvider将自行获取数据和主题道具,并且当它包含任何子组件时,我还想访问子组件中的道具“数据”和“主题”。 我们怎样才能实现它?

class FetchProvider 
{

   proptypes= {
     data: PropTypes.shape({}),
     theme: PropTypes.shape({})
   }

   render()
   {
     // do some
   }

   mapStateToProps()
   {
      return {data, theme};
   }
}

class ChildComponent
{

   proptypes= {
     name: PropTypes.shape({})
   }

   render()
   {
     const{data, them} = this.props; // is this possible here?
     // do some
   }
}

如果我尝试将组件放在上面,如下所示。

<FetchProvider>
   <ChildComponent name="some value"/>  //how can we access parent component props here? without passing them down
<FetchProvider/>

这正是反应上下文的全部内容。

无论嵌套有多深, Consumer都可以访问Provider公开的数据。

// Context lets us pass a value deep into the component tree
// without explicitly threading it through every component.
// Create a context for the current theme (with "light" as the default).
const ThemeContext = React.createContext('light');

class App extends React.Component {
  render() {
    // Use a Provider to pass the current theme to the tree below.
    // Any component can read it, no matter how deep it is.
    // In this example, we're passing "dark" as the current value.
    return (
      <ThemeContext.Provider value="dark">

<Toolbar />
      </ThemeContext.Provider>
    );
  }
}

// A component in the middle doesn't have to
// pass the theme down explicitly anymore.
function Toolbar(props) {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

function ThemedButton(props) {
  // Use a Consumer to read the current theme context.
  // React will find the closest theme Provider above and use its value.
  // In this example, the current theme is "dark".
  return (
    <ThemeContext.Consumer>

{theme => <Button {...props} theme={theme} />}
    </ThemeContext.Consumer>
  );
}

这是一个小的运行示例

注意这是 react v16 上下文 API。

您的用例可以通过使用React context来解决。 在 Context 的帮助下,被provided 包裹的任何孩子都可以成为Provider 提供的数据的消费者

在你的情况下,你可以像这样使用它

上下文.js

export const FetchContext = React.createContext();

提供者.js

import { FetchContext } from 'path/to/context.js';
class FetchProvider extends React.Component
{

   proptypes= {
     data: PropTypes.shape({}),
     theme: PropTypes.shape({})
   }

   render()
   {
        const { data, theme, children } = this.props;
        return (
             <FetchContext.Provider value={{ data, theme}}>
                   {children}
             </FetchContext.Provider>
        )
   }

   mapStateToProps()
   {
      return {data, theme};
   }
}

子组件.js

class ChildComponent extends React.Component
{

   proptypes= {
     name: PropTypes.shape({})
   }

   render()
   {
     const{data, them} = this.props; // use it from props here
     // do some
   }
}

export default (props) => (
     <FetchContext.Consumer>
           {({ data, theme }) => <ChildComponent {...props} data={data} theme={theme} />}
     </FetchContext.Consumer>
)

然而,鉴于您已经在使用 Redux,它建立在 Context 的概念之上,您不妨使用 redux 并访问子组件中的值,因为它们与从 Redux 存储提供给子组件的值相同由父母。

class ChildComponent extends React.Component
{

   proptypes= {
     name: PropTypes.shape({})
   }

   render()
   {
     const{data, them} = this.props; // use it from props here
     // do some
   }
}

const mapStateToProps = (state) => {
     return {
          data: state.data,
          theme: state.theme
     }
}

您可以使用React.Children迭代子元素,并使用React.cloneElement将您想要发送给新克隆元素的任何道具传递给。

前任:

class Parent extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    const { children } = this.props;
    const newChildren = React.Children.map(children, child =>
      React.cloneElement(child, { myProp: 'test' }));

    return(
      <View>
        {newChildren}
      </View>
    )
  }
}

您是否正在寻找:

class MyParent extends Component {
    render() {
        return <MyChild {...this.props}>
            // child components
        </MyChild>
    }
}

这会将传入MyParent所有道具传递给正在渲染的MyChild

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM