简体   繁体   中英

ReactJS: how to add a functionality to any React Component by default in my app

Let say this is how I pass in functions to MyComponent :

<MyComponent
  setMyValue={this.setMyValue}
  setYourValue={this.setYourValue}
  updateTheirValues={this.updateTheirValues}
  updateHerValue={this.updateHerValue}
  loadHisValue={this.loadHisValue}

  {...this.props}
/>

Is there anyway I can add a functionality - called something like _passFunctions to any component in my app to do:

<MyComponent
    __passFunctions={[
      this.loadHisValue,
      this.updateHerValue,
      this.updateTheirValues,
      this.setYourValue,
      this.setMyValue
    ]}
    {...this.props}
  />

You can use object spread in component

Example

 const MyComponent = (props) => { console.log(props); return <div></div> } const App = () => { const loadHisValue = () => {}; const updateHerValue = () => {}; const updateTheirValues = () => {}; const setYourValue = () => {}; const setMyValue = () => {}; const functionalities = { loadHisValue, updateHerValue, updateTheirValues, setYourValue, setMyValue }; return <div> <MyComponent {...functionalities}/> </div> } ReactDOM.render( <App/>, document.getElementById('root') );
 <script src="https://unpkg.com/react/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> <div id="root"></div>

to any component in my app to do:

You can extract functionalities to separate module and use it in every component in a way above or you can follow best practices and use React.Context or Redux

You could use pick from underscore or similar to extract specific keys from an object eg like:

<MyComponent
  { ..._.pick(
    this,
    'loadHisValue',
    'updateHerValue',
    'updateTheirValues',
    'setYourValue', 
    'setMyValue'
  )}
  {...this.props}
/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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