2017-04-18 2 views
-1

私は入力ボックスを含む反応コンポーネントを持っています。私は、入力ボックスが空でないことを確認したい。 componentDidMountキーの文字列でsetStateを更新します

は、私は次の関数を実行します。

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

あなたはこの 'this.setState({[inputType]:真})のような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>

関連する問題