【问题标题】:React understand only random keys?React 只理解随机键?
【发布时间】:2017-02-16 08:57:04
【问题描述】:

我遇到了非常奇怪的情况。如果未通过验证,我需要更改输入值:

if (!isValid) {
  //if invalid set previous value
  this.timeInput.value = previous value;
}

我使用的是masked input,但使用香草输入时的行为完全一样。

我的输入更新,就在下一次重新渲染之前被调用。 这是我的第一个问题 - 为什么? 好的,经过一些研究,我找到了解决方案 - 将键添加到输入中,正如所说的那样添加 -

<input key={Math.random()}/>

还有它的工作!但最奇怪的是,当我尝试将值从随机更改为我的 id 属性时,类似于 -

key={Number(this.props.id)}

它不起作用!为什么?一个区别只是我的 id 是整数(如3),但Math.random 返回类似0.21421214124 的东西。

组件:

handleTimeBoxBlur = (e) => {
    const newTime = convertToSeconds(e.target.value)
    //if nothing was changed
    if (newTime === this.props.slide.seconds) {
      return;
    }

    const isValid = this.props.checkValidation(this.props.slide.id, newTime)
    if (!isValid) {
       //if invalid set previous value
       this.timeInput.value = formatSS(this.props.slide.seconds);
       setTimeout(() => this.setState({isValid : true}), 6000) //remove field highlighting after 8 seconds
    }

    this.setState({isValid : isValid})
 }

 render() {
    <input 
      key={Math.random()}  
      styleName={inputStyleName}
      onBlur={this.handleTimeBoxBlur}
      ref={ref => this.timeInput = ref} 
      defaultValue={formatSS(this.props.slide.seconds)} />
 }

【问题讨论】:

  • 你使用的是哪个 React 版本?
  • 我正在使用 React 15.4.2
  • “它不起作用”是什么意思?你可以说得更详细点吗?究竟是什么不起作用?
  • 输入正在更新,但在下一次render() 调用时返回他的值
  • 你能发布组件的代码吗?代码太少很难理解

标签: javascript reactjs random react-jsx ref


【解决方案1】:

发生这种情况是因为您使用的是uncontrolled input component(TL;DR,您没有任何 onChange 方法),我想知道它在您更改密钥之前是否有效。我尝试了两种方法,但没有奏效。正如here 所述,您需要使用受控组件来获得预期的行为。

试试这样的:

  constructor(props) {
    super(props)
    this.state = {
      isValid: false,
      textValue: props.slide.seconds
    }

    this.handleTimeBoxBlur = this.handleTimeBoxBlur.bind(this)
    this.handleChange = this.handleChange.bind(this)
  }

  handleChange(e) {
    this.setState({ textValue: e.target.value })
  }

  handleTimeBoxBlur(e) {
    const newTime = this.state.textValue
    //if nothing was changed
    if (newTime === this.props.slide.seconds) {
      return;
    }

    const isValid = this.props.checkValidation(this.props.slide.id, newTime)

    if (!isValid) {
       //if invalid set previous value
       this.setState({textValue: this.props.slide.seconds});
       setTimeout(() => this.setState({isValid : true}), 6000) //remove field highlighting after 8 seconds
    }

    this.setState({isValid : isValid})
  }

   render() {
    return (
      <MaskedInput 
        key={this.props.slide.id}  
        mask={'11a'}
        onBlur={this.handleTimeBoxBlur} 
        value={this.state.textValue} 
        onChange={this.handleChange}
        />
        );
 }

【讨论】:

  • 谢谢回答,但由于几个原因我不能在这里使用受控组件
  • 那么你不能使用 MaskedInput 组件,因为它们坚定地声明它是使事情正常工作的唯一方法
猜你喜欢
  • 2011-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多