繁体   English   中英

如何在 Reactjs 中访问组件 defaultProps 中的状态

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

我需要通过类的defaultProps获取要访问的组件的状态,这是我的代码:

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}抛出错误,因为它在类之外。 如何获取password状态并将其传递到Headcomponent.defaultProps

恐怕你不能。 getDefaultProps 在组件启动之前被调用。 您不能像那样在组件外部使用状态。

我不完全明白你想要做什么。 请解释。

如果您尝试为密码字段之类的内容设置默认属性,那么您可以将其设置为字符串值。 如果您希望默认密码道具为“password123”,则将其设置为“password123”。

当我试图理解这一点时,目前还不清楚您是如何在 React 组件中设置 this.state.password 的。 您的构造函数中有一个浮动的 setState 调用,但它没有列出密码。

听起来您正在尝试将默认道具设置为某人最终会在未来某个时候在表单中键入的值。 您不能将默认值设置为某人将来决定的内容。 那将需要时间旅行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM