在 react 的输入标签中添加状态变量值


class Filter extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
       placeholder: true,
       variableValue: '',
      }
   }
  render() {
    return (
     <input placeholder={this.state.placeholder ? "select filter" : this.state.variableValue} />
  )
 }}

现在,每当变量输入从另一个地方定义的某个函数进入状态时。如果变量在状态中有一些值,我想更改占位符值。

有没有办法在一行中做到这一点

最好只使用一个状态变量,如果未设置该变量,则使用默认值。

class Filter extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            placeholder: null,
        };
    }
    render() {
        return <input placeholder={this.state.placeholder || 'select filter'} />;
    }
}

我不太确定为什么要将值放在占位符中,但正确的方法是:

class Filter extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
       //placeholder: true,
       variableValue: '',
      }
      this.changeValue=this.changeValue.bind(this)
   }
  changeValue(event){
     this.setState({variableValue:event.target.value})
   }
  render() {
    return (
     <input placeholder="select filter"  value={this.state.variableValue} onChange={changeValue} />
  )
 }}

在这里,我们声明输入字段的值将是状态variableValue,并定义一个处理此输入字段中任何更改的方法。

最新更新