我正在尝试制作Todo应用程序,但我被卡住了,我无法继续进行。请帮忙
var Todo= React.createClass({
save() {
this.refs.newText.value
},
render(){
return(
<div className="list">
<h1> TO-DO List</h1>
<input type="text" ref="newtext" defaultValue={this.props.children} />
<button onclick={this.save} className="btn btn-primary glyphicon glyphicon-floppy-saved">
</button>
<ul>
<li>{this.target.value}</li>
</ul>
</div>
)
},
});
答案 0 :(得分:0)
维护一个状态,您将在其中添加新添加的项目,然后迭代它以在视图中显示。此外,您不应该使用字符串引用,而应该按照react-docs的建议使用ref callbacks
。此外,onclick
按钮应为camelcase
,如onClick
var Todo= React.createClass({
getInitialState() {
return {
todos: []
}
},
save() {
var todos = [...this.state.todos];
todos.push(this.newText.value);
console.log(todos)
this.setState({todos});
},
render(){
return(
<div className="list">
<h1> TO-DO List</h1>
<input type="text" ref={(ip) => {this.newText = ip}}/>
<button onClick={this.save} className="btn btn-primary glyphicon glyphicon-floppy-saved">Save
</button>
<ul>
{this.state.todos.map(function(todo) {
return <li>{todo}</li>
})}
</ul>
</div>
)
},
});
ReactDOM.render(<Todo/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.min.js"></script>
<div id="app"></div>
答案 1 :(得分:0)
要添加Shubnam的答案,请考虑使用ES6类并在构造函数中初始化状态,因为现在推荐使用ES6类。现在不推荐使用React.createClass,并在控制台上显示警告。检查此代码,注意您需要绑定save方法。
请查看以下链接以获取更多信息:
https://facebook.github.io/react/blog/#migrating-from-react.createclass
https://toddmotto.com/react-create-class-versus-component/
class Todo extends React.Component {
constructor(props) {
super(props);
this.state={todos:[]};
}
save() {
var todos = [...this.state.todos];
todos.push(this.newText.value);
this.setState({todos});
}
render(){
return(
<div className="list">
<h1> TO-DO List</h1>
<input type="text" ref={(ip) => {this.newText = ip}}/>
<button onClick={this.save.bind(this)} className="btn btn-primary glyphicon glyphicon-floppy-saved">Save
</button>
<ul>
{this.state.todos.map(function(todo) {
return <li>{todo}</li>
})}
</ul>
</div>
)
}
};
ReactDOM.render(<Todo/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
答案 2 :(得分:0)
`` 从'react'导入React,{组件}; 从'./nav'导入Nav;
Delete_Contect类扩展了组件{
constructor(props)
{
super(props);
this.state={
name:'vishal',
name_add:[1,2,4]
};
this.Change = this.Change.bind(this);
this.Add_data = this.Add_data.bind(this);
}
Change()
{
this.setState(
{
name:'boss'
}
)
}
Add_data(e)
{
const newContect = this.newText.value
this.setState({
name_add: [...this.state.name_add, newContect]
})
}
render() {
return (
<div>
{this.state.name_add.map((number) => {
return(
<li>{number}</li>
)
})}
<input type="text" ref={(ip) => {this.newText = ip}} />
<button onClick={this.Add_data}>submit</button>
</div>
);
}
}
export default Delete_Contect;