私は、テーブルに投稿を追加するアプリケーションに取り組んでいます。私の下のコードは動作しません。あなたは、あなたがバベルを使用している場合Reactを使用して投稿を追加するには?
あなたのコンストラクタで
this.handleAddNew = this.handleAddNew.bind(this);
を追加する必要がhandleAddNew
this
に結合していなかった
Uncaught TypeError: Cannot read property 'props' of null(…) for function handleAddNew()
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
number:'1',
name:'gogo',
title:'',
views:'10',
likes:'22',
date:'1.1.1111'
};
}
addPost(title){
this.state.title.push(title);
this.setState({
post: this.state.title
});
}
render() {
return (
<div>
<AddPost addNew={this.addPost} />
<table>
<thead>
<Thead/>
</thead>
<tbody>
<Row number={this.state.number}
name={this.state.name}
title={this.state.title}
views={this.state.views}
likes={this.state.likes}
date={this.state.date}/>
</tbody>
</table>
</div>
);
}
}
class AddPost extends React.Component{
constructor(props) {
super(props);
this.state = {
newPost: ''
}
this.updateNewPost = this.updateNewPost.bind(this);
}
updateNewPost(e){
this.setState({newPost: e.target.value});
}
handleAddNew(){
this.props.addNew(this.state.newPost);
this.setState({newPost: ''});
}
render(){
return (
<div>
<input type="text" value={this.state.newPost} onChange={this.updateNewPost} />
<button onClick={this.handleAddNew}> Add Post </button>
</div>
);
}
}
class Thead extends React.Component {
render() {
return (
<tr>
<td id='number'>ID</td>
<td id='name'>User name</td>
<td id='title'>Post title</td>
<td id='views'>Views</td>
<td id='likes'>Likes</td>
<td id='date'>Created at</td>
</tr>
);
}
}
class Row extends React.Component {
render() {
return (
<tr>
<td>{this.props.number}</td>
<td>{this.props.name}</td>
<td>{this.props.title}</td>
<td>{this.props.views}</td>
<td>{this.props.likes}</td>
<td>{this.props.date}</td>
</tr>
);
}
}
export default App;
バインドを追加していただきありがとうございます。しかし、次の問題があります。Uncaught TypeError:未定義(...)のプロパティ 'title'を読み取ることができません。 this.state.title.push(title)は読まない。 2つの理由からthis.state.title –
に値をプッシュすると思った。 1. push()メソッドは配列の最後に要素を追加します。 'this.state.title'は文字列です。 2.状態を変更するには、以下の1行を実行したようにします: 'this.setState({title:this.state.title});または、それらが同じ名前であるため、これを短くすることができます。 setState({title}); '両方とも組み合わせることができます: 'this.setState({title、post:this.state.title});' – Robiseb
OK。私はそれを持っている: this.addPost = this.addPost.bind(this); } addPost(タイトル){ this.setState({title}); } ありがとうございます! :) –