interface states and props in typescript react

后端 未结 1 1905
慢半拍i
慢半拍i 2021-01-30 17:09

I\'m working on a project that uses typescript as well as react and am new to both. My questions is about interface in typescript and how that relates to props and states. What

1条回答
  •  闹比i
    闹比i (楼主)
    2021-01-30 17:38

    It's not clear what you're asking exactly, but:

    props: are the key/value pairs that are being passed from the parent of the component and a component should not change it's own props, only react to changes of props from the parent component.

    state: kinda like props but they are changed in the component itself using the setState method.

    the render method is called when the props or state have changed.

    As for the typescript part, the React.Component takes two types as generics, one for the props and one for the state, your example should look more like:

    interface MyProps {}
    
    interface MyState {
        hero: string;
        whatIs: string;
        aboutOne: string;
        aboutTwo: string;
        testimonial: string;
        footer: string;
    }
    
    class Root extends React.Component   {
        constructor(props) {
            super(props);
    
            this.state = {
                // populate state fields according to props fields
            };
        }
    
        render() {
            return (
                
    ) } }

    As you can see, the MyState interface defines the fields which are later used in the component this.state member (I made them all strings, but they can be anything you want).

    I'm not sure whether or not those fields actually need to be in state and not in props, but that's you call to make.

    0 讨论(0)
提交回复
热议问题