javascript - 禁用无状态组件中的按钮 - React

标签 javascript reactjs react-component

我试图弄清楚如何在仅使用 prop 的无状态组件中设置禁用字段。无状态组件有一个输入字段,如果为空,我想禁用同一组件中的提交按钮。我能够通过子项的 Prop 来更新父项的状态,因此希望保持它没有状态,但开始认为我可能需要它来检查按钮是否可以启用。

我尝试了使用 refs 等不同的方法。这是我的一个示例代码和盒子项目

https://codesandbox.io/s/840kkk03l

无状态属性是:

const Childprop = function(props) {
  function handleNameChange(e) {
    e.preventDefault();
    props.onNameChange(e.target.newName.value);
  }
  function checkDisabled() {
    var input = document.getElementById("input");
    if (input.value === "") {
      return true;
    } else {
      return false;
    }
  }
  return (
    <p>
      The logged in user is: {props.nameProp}
      <form onSubmit={handleNameChange}>
        <input name="newName" type="text" id="input" />
        <input type="submit" disabled={checkDisabled} />
      </form>
    </p>
  );
};

谢谢

最佳答案

我将仅使用本地状态作为输入的值。这将使其成为 controlled component .

class Childprop extends React.Component {
    state = {
        newName: ''
    }

    handleNameChange = (e) => {
        e.preventDefault();
        props.onNameChange(this.state.newName);
        this.setState({ newName: '' });
    }

    render() {
        return (
            <div>
                The logged in user is: {props.nameProp}
                <form onSubmit={handleNameChange}>
                    <input name="newName" type="text" id="input" onChange={(e) => this.setState(e.target.value)} value={this.state.newName} />
                    <input type="submit" disabled={this.state.newName.length === 0} />
                </form>
            </div>
        );
    }
};

关于javascript - 禁用无状态组件中的按钮 - React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51902086/

相关文章:

javascript - 为什么 console.dir ('' ) 打印 "no properties"?

javascript - 无法在函数内部编辑数组

javascript - 当使用新 Prop 调用渲染时,React JS 未完全更新 View

javascript - 在 React 中使用 Array.Map() 返回子数组

javascript - React Redux - 当他们返回该页面时如何在特定位置使用

javascript - 如何简化ReactJS中的setTimeout

javascript - setTimeout 在 for 循环中传递参数

javascript - 模仿 Array.from 方法的静态方法在 Javascript 中不起作用

javascript - React - 使用状态对子组件数组进行排序

javascript - "TypeError: kinds.map is not a function."React.js