简体   繁体   中英

How do I access state in a component's defaultProps in Reactjs

I need to get the state of the component to be accessed by the defaultProps of a class, here is my code:

class Headcomponent extends React.Component {

    constructor(props) {

        super(props);
        this.state = {
            email: '',
            password: '',
            formErrors: {
                email: '',
                password: ''
            },
            emailValid: false,
            passwordValid: false,
            formValid: false,
            items: [],

        }
    }


    this.setState({
        formErrors: fieldValidationErrors,
        emailValid: emailValid,
        passwordValid: passwordValid
    }, this.validateForm);
}

validateForm() {
    this.setState({
        formValid: this.state.emailValid &&
            this.state.passwordValid
    });
}


render() {
    return ( <
        Form fields = {
            this.props.form
        }
        buttonText = "Submit" / >
    );
}
}    

Headcomponent.propTypes = {
    form: PropTypes.array,
};

Headcomponent.defaultProps = {
    form: [{
            label: 'label1',
            placeholder: 'Input 1',
            value: {
                this.state.password
            } //this throws an error
        },
        {
            label: 'label2',
            placeholder: 'Placeholder for Input 2',
        },
    ],
};

export default Headcomponent;

{this.state.password} throws an error because it is outside of the class. How do I get the state of password and pass it inside Headcomponent.defaultProps ?

I'm afraid you can't. getDefaultProps is called before the component is initiated. You cannot use state outside of the component like that.

I don't fully understand what you are trying to do. Please explain.

If you are trying to set a default prop for something like a password field then you can just set it as a string value. If you want the default password prop to be 'password123' then set it to 'password123'.

As I try to understand this, it is unclear how you are setting this.state.password in your react component. You have a floating setState call in your constructor but it doesn't list the password.

It sounds like you are trying to set the default props to the value that someone will eventually type in a form, at some point in the future. You can't set the default to something someone decides in the future. That would require time travel.

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