2017-04-18 26 views
-1

我有一個包含輸入框的反應組件。我想確保輸入框不是空的。使用密鑰的字符串更新setState

componentDidMount我運行下面的功能:

this.validateInputLength(this.state.first_name, 'firstNameValid');

,你可以看到我傳遞的this.state.first_name值和字符串'firstNameValid'

問題是'firstNameValid'未設置組件的狀態。 I was under the impression,我可以將狀態對象的鍵作爲字符串傳遞,並且它會更新,但這似乎不起作用。

有關更多上下文,請參閱下面的完整代碼。

class Test extends Component { 
 

 
    constructor(props) { 
 
    super(props) 
 

 
    this.state = { 
 
     first_name: '', 
 
     last_name: '', 
 
     firstNameValid: true, 
 
     lastNameValid: true 
 
    }; 
 
    
 
    this.validateInputLength = this.validateInputLength.bind(this); 
 
    } 
 

 
    componentDidMount() { 
 

 
    this.validateInputLength(this.state.first_name, 'firstNameValid'); 
 
    this.validateInputLength(this.state.last_name, 'lastNameValid'); 
 

 
    } 
 

 

 
    validateInputLength(value, inputType) { 
 

 
    if (value.length <= 0) { 
 

 
     this.setState({ 
 
     inputType: false 
 
     }); 
 

 
    } else { 
 

 
     this.setState({ 
 
     inputType: true 
 
     }); 
 

 
    } 
 
    } 
 

 
    render() { 
 
    ........ 
 
    } 
 
}

+0

您需要大約'inputType'方括號這樣'this.setState({[的inputType]:真正})' –

+2

我要添加一個回答它被標記爲重複之前,但在這裏是編寫功能更好的方法: 'validateInputLength(值,的inputType){ this.setState({ [的inputType]:value.length> 0 }) }' – ndbroadbent

回答

0

您可以在方括號包裹,實現你追求的。

var testing = "testable"; 
 

 
var test = { 
 
\t [testing]: "value in [testing]" 
 
}; 
 

 
document.getElementById("value").innerText = test.testable;
<p id="value"></p>

相關問題