设置输入的默认值

时间:2020-03-26 11:57:19

标签: reactjs

我想为ant设计组件设置一个默认值,但是我不能。我没有出现。为什么?以及如何设置默认值?

链接到应用程序:https://codesandbox.io/s/hide-already-selected-ant-design-demo-ezmrw

2 个答案:

答案 0 :(得分:1)

对于完全受控的组件(值,绑定onChange)

您不需要设置defaultValue

直接使用默认值初始化状态是可以的。

state = {selectedItems: [OPTIONS[0]]};
...
// defaultValue={"test"}
import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Select } from "antd";

const OPTIONS = ["Apples", "Nails", "Bananas", "Helicopters"];

class SelectWithHiddenSelectedOptions extends React.Component {
  state = {
    selectedItems: [OPTIONS[0]]
  };

  handleChange = selectedItems => {
    this.setState({ selectedItems });
  };

  render() {
    const { selectedItems } = this.state;
    const filteredOptions = OPTIONS.filter(o => !selectedItems.includes(o));
    return (
      <Select
        placeholder="Inserted are removed"
        value={selectedItems}
        onChange={this.handleChange}
        style={{ width: "100%" }}
      >
        {filteredOptions.map(item => (
          <Select.Option key={item} value={item}>
            {item}
          </Select.Option>
        ))}
      </Select>
    );
  }
}

ReactDOM.render(
  <SelectWithHiddenSelectedOptions />,
  document.getElementById("container")
);

Edit Hide Already Selected - Ant Design Demo

答案 1 :(得分:0)

从道具中移除value,一切都会开始正常运行