简体   繁体   中英

Is there a way to export setState outside stateless components in react?

Consider this example

export function InsideHoc(props){
   const [A, setA] = useState(false);

   return({if(A) && (<h1>Print something</h1>)});
}

In another file

import {A, setA} from './inside-file';

function ToggleFromOutside(){
   return(<p onClick={setA(!A)}>Verify</p>);
}

Can setA be exposed outside so that the state of this component be changed from outside? I know this can be done through redux. But without using this, is there a way to change the state of one component?

Structure is like this

import {withCreateHOC} from './external';
import childComponent from './child';


class A extends React.Component {
   render(){
      <Another menus={(item) => <MenuItems object={item} />}
       />
   }
}

 export default withCreateHOC(A, {custom: childComponent, title: 'Add'});

//withCreateHOC renders modal here as well as it has a button to toggle the state. Same state should be used from below function

function MenuItems(){
   return(<button onClick={displayModal}>)
}

Yes.

You can lift the state in that case. This works good if you don't need to pass down the setState to far down the tree.

If you don't want to pass the setState function all the way down the React element tree, you will need to use context , redux or some other state handling.

Example state lift

export function Parent(){
   const [message, setMessage] = useState("Hello World");

   return (
     <>
      <Child1 message={message} />
      <Child2 changeMessage={setMessage} />
     </>

   );
}

// Can be in other file
function Child1(props){
   return(<p>{props.message}</p>);
}

// Can be in other file
function Child2(props){

   return(
     <a onClick={() => props.changeMessage("Changed")}>  
       I can change things in other components.
     </a>
   );
}

Example of React tree with shared context/redux

<WithRedux>
  <App>
    <Navigation />
    <Modal />
    <PageRenderer />
    <SomeList>
      <ListItem />
      <ListItem />
    </Somelist>
  </App>
<WithRedux>

All the children of the WithRedux component can access the state and modify it.
(PS: You can wrap the App with the HOC withRedux etc, this example is just for visualization)

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