首页 > 解决方案 > Reactjs 在 props 数组中设置状态

问题描述

我是 React.js 的新手,正在尝试构建表单验证。

有 Btn 组件。

const MyBtn = ({opts}) => {

   if(!opts) {
      opts = {};
   }

   return (
      <button {...opts}}>{opts.value}</button>
   )
}

Home.js 是一个登录页面。我不会添加您可能不需要解决此问题的其他代码。

class Home extends Component {
    state = {
       formValid: false
    }

   regexCheck = {
       disabled : {this.state.formValid},
       value: "LogIn",
       type: "submit"
   }

   render(){
      return(
        <MyBtn opts={this.regexCheck}/>
      )
    }
}

//output that I'm trying to get
<button type="submit" disabled={this.state.formValid}>LogIn</button>

我收到一个错误,我无法在道具中调用 {this.state.formValid}。因为这是一个保留字。(对不起我的英语不好。)我觉得我完全错了。

无论如何,我认为我可以为此使用 getDerivedStateFromProps 方法......?所以我在 Home.js 中添加了这个但没有用。

static getDerivedStateFromProps(nextProps, prevState){
    if(prevState.formValid !== nextProps.formValid){
        return { formValid: nextProps.formValid };
    }
    return null;
}

如您所见,我仍然对道具和状态感到困惑。啊,但我还是要继续做这个项目。请给我任何想法来解决这个问题。

标签: reactjs

解决方案


这是无效的语法:

disabled : {this.state.formValid},

你只是想要:

disabled : this.state.formValid,

推荐阅读