简体   繁体   中英

How can I pass props from one component to another withour Redux

I have this kind of jsx and I want to pass number value from SendNumberPage to CheckNumberPage.

App.js

           <EditNumberPage/>
            <br/>
            <SendNumberPage/>
            <br/>
            <CheckNumberPage/>

SendNumberPage.js

function onChangeHandler(event) {
        setState({
            ...state,
            number: event.target.value
        })
    }

I tried using React.createContext but it didn't work for me. Please Help

sendNumberPage.js

    const [state, setState] = useState(
        {
            number: '+99979787'
        }
    )

   const NumberContext = React.createContext()

   return (

<NumberContext.Provider value={state.number}>
<div>
....
....
</div>
</NumberContext.Provider>
  )

checkNumberPage.js

const CheckNumberPage = () => {
const value = useContext(NumberContext)
        console.log(value)
return (
.......
)
}

Console says Attempted import error: 'NumberContext' is not exported from './SendNumberPage'.

Depending on how complex your app is you may want to do this in different ways.

Using react context api is a good way to do it, and it is scalable and suitable for all app sizes.

You should check out the react tutorials for that.

If your app is very small (1 layer) and you just want a 'quick fix' you could pass a change listener callback to one component and update the props in the other component.

       <EditNumberPage/>
            <br/>
            <SendNumberPage onChange={(n) => {setNumber(n)} />
            <br/>
            <CheckNumberPage number={number}/>

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