简体   繁体   中英

passing prop to state in react js

const [nav, setNav] = useState({
firstPage: "active",
});

I want to pass my prop as value to state firstpage how I do this in correct manner

const addNavi = (prop) => {

//want to pass prop in to my state value
}

You can use destructuring assignment the props in the argument of the AddNavi component signature (in parenthesis) and then pass it in as the first argument in useState , which will set the initial state of nav :

import React, { useState } from 'react';

const AddNavi = ({ firstPage }) => {

  const [nav, setNav] = useState(firstPage);
}

Hint : ReactJS components MUST start with upper case characters like AddNav not addNav .

我想你想用 props 值初始化状态,你可以像下面这样传递。

const [nav, setNav] = React.useState({...props.firstPage});

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