简体   繁体   中英

react typescript what type is setState?

I am passing a setState as a prop from a parent component to modify the state on a child component of that parent, on typescript when creating a interface, what is the type of setState?

function App() {
    const [links, setLinks] = useState();

    return (
        <div className='App'>
            <Sidebar setLinks={setLinks} />
            <Main />
        </div>
    );
}

on child:

interface SidebarProps {
    setLinks: ??????;
}


const Sidebar: React.FC<SidebarProps> = ({ setLinks }) => {
    return (
        <div style={sidebar}>
            <button onClick={() => setLinks('1')}>pic1</button>
            <button onClick={() => setLinks('1')}>pic2</button>
        </div>
    );
};

React.Dispatch<React.SetStateAction>

Above string can be replaced if you infer a type for setState (eg I assumed setState<string>() )

Refer the below code:-

function App() {
    const [links, setLinks] = useState<string>();

    return (
        <div className='App'>
            <Sidebar setLinks={setLinks} />
            <Main />
        </div>
    );
}


interface SidebarProps {
    setLinks: Function;
}


const Sidebar: React.FC<SidebarProps> = ({ setLinks }) => {
    return (
        <div style={sidebar}>
            <button onClick={() => setLinks('1')}>pic1</button>
            <button onClick={() => setLinks('1')}>pic2</button>
        </div>
    );
};

This is my example based on Kyrill's answer.

interface Props {
  editMode: boolean
  setEditMode: React.Dispatch<React.SetStateAction<boolean>>
}

export default function NavToolbar(props: Props): ReactElement {
 
...

I'm sure there are better ways to do this though :)

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