2017-02-16 72 views
0

我真的很奇怪。我需要改變輸入的值,如果其沒有通過驗證:反應只懂隨機密鑰?

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

我使用masked input,但與香草的輸入行爲完全一致。

而我得到的情況是我的輸入更新,只是在下次調用之前被調用。 它是我的第一個問題 - 爲什麼?好了,經過一番研究,我找到了解決辦法 - 添加鍵輸入,如說有加 -

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

及其工作!但奇怪的是,當我試圖從隨機的值更改爲我的id屬性,像 -

key={Number(this.props.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)} /> 
} 
+0

起反應的版本您使用的? – juancab

+0

Im使用React 15.4.2 –

+0

你是什麼意思,「它不工作?」你可以說得更詳細點嗎?什麼不工作? – juancab

回答

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} 
     /> 
     ); 
} 
+0

THX的答案,但我不能在這裏使用controllled組件有以下幾個原因 –

+0

那麼你就不能使用MaskedInput組件,因爲他們堅定地表示,它是使事情順利進行的唯一途徑 – juancab