2017-01-31 4 views
0
import React from 'react'; 

class App extends React.Component { 

    constructor() { 
     super(); 

     this.state = { 
      data: 'First Comes First Serves' 
     } 

     this.updateState = this.updateState.bind(this); 
    }; 

    updateState(e) { 
     console.log(e); 
//  console.log(e.target); 
     this.setState({data: e}); 
    } 

    render() { 
     return (
      <div> 
       <Content myDataProp = { this.state.data } updateStateProp = { this.updateState }></Content> 
      </div> 
     ); 
    } 
} 

class Content extends React.Component { 
    render() { 
     return (
      <div> 
       <input type="text" value={ this.props.myDataProp } id="id" /> 
       <div> 
        <button onClick={ this.props.updateStateProp(document.getElementById('id').value )}>Click</button> 
       </div> 
       <h3>{ this.props.myDataProp }</h3> 
      </div> 
     ); 
    } 
} 


export default App; 

エラー; 未知の型エラー:nullのプロパティ '値'を読み取れません実数値null DOM操作

私はReactで非常に新しいです。ここで

は、入力値は「最初に来..」(私は仮定)として割り当てられていますが、エラーは、事前に

感謝を表示されます。

答えて

1

Reactを使って作業しているときは、getElementByIdのようにDOM上で直接動作する操作を完全に忘れることが最善です。彼らはまったく、あるいは予期しない方法で働かないでしょう。

代わりに、優秀なReact forms documentationをご覧ください。

Reactでフォームを行う慣習的な方法は、inputonChangeイベントハンドラを実装し、現在の値をコンポネントの状態に格納することです。次に、ユーザーがボタンを押したときにアクセス権を使用して使用できます。

+0

ありがとうございます。それは問題を解決した – NewPHPer

0

私はティモと全く同意します。私はあなたのためのコンポーネントを変更しました:

class App extends React.Component { 

    constructor() { 
    super(); 

    this.state = { 
     data: 'First Comes First Serves' 
    } 

    this.updateState = this.updateState.bind(this); 
    }; 

    updateState(e) { 
    this.setState({ data: e.target.value }); 
    } 

    render() { 
    return (
     <div> 
     <Content myDataProp={this.state.data} updateStateProp={this.updateState}></Content> 
     </div> 
    ); 
    } 
} 

class Content extends React.Component { 
    render() { 
    return (
     <div> 
     <input type="text" onChange={this.props.updateStateProp} id="id" /> 
     <div> 
      <button onClick={this.props.updateStateProp}>Click</button> 
     </div> 
     <h3>{this.props.myDataProp}</h3> 
     </div> 
    ); 
    } 
} 


export default App; 

私はあなたがそれを働かせるかどうか教えてください。