gpt4 book ai didi

javascript - react .js : data not getting populated

转载 作者:数据小太阳 更新时间:2023-10-29 06:06:49 25 4
gpt4 key购买 nike

我正在 React.js 网站上做教程。这是我的代码:

<html>
<head>
<title>Hello React</title>
<script src="http://fb.me/react-0.8.0.js"></script>
<script src="http://fb.me/JSXTransformer-0.8.0.js"></script>
<script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
</head>
<body>
<div id="content"></div>
<script type="text/jsx">
/**
* @jsx React.DOM
*/
// The above declaration must remain intact at the top of the script.
// Your code here
var commentsData = [
{author: "Pete Hunt", text: "This is one comment"},
{author: "Jordan Walke", text: "This is *another* comment"}
];

var CommmentBox = React.createClass({
getInitialState: function() {
return {data: []};
},
componentWillMount: function() {
this.loadComments();
},
render: function() {
return (
<div className='commmentBox'>
<h1>Comments</h1>
<CommentList data={this.state.data} />
<br />
<CommentForm onCommentSubmit={this.handleCommentSubmit} />
</div>
);
},
handleCommentSubmit: function(comment) {
commentsData.push(comment);
this.loadComments();
},
loadComments: function() {
console.log(commentsData.length);
this.setState({data: commentsData});
}
});

var CommentList = React.createClass({
render: function() {
var commentNodes = this.props.data.map(function(comment) {
return <Comment author={comment.author} text={comment.text} />;
});
return (
<div className='commentList'>
{commentNodes}
</div>
);
}
});

var CommentForm = React.createClass({
render: function() {
return (
<form className='commentForm' onSubmit='handleSubmit'>
<input type='text' placeholder='Your name' ref='author'/>
<input type='text' placeholder='Your comment' ref='text'/>
<input type='submit' value='Post' />
</form>
);
},
handleSubmit: function() {
var author = this.refs.author.getDOMNode().value.trim();
var text = this.refs.text.getDOMNode().value.trim();
this.props.onCommentSubmit({author: author, text: text});
this.refs.author.getDOMNode().value = '';
this.refs.text.getDOMNode().value = '';
return false;
}
});

var Comment = React.createClass({
render: function() {
return(
<div className='comment'>
<br />
<h3 className='commentAuthor'>
{this.props.author} wrote:
</h3>
<h3 className='commentText'>
{this.props.text}
</h3>
</div>
);
}
});

React.renderComponent(
<CommmentBox />,
document.getElementById('content')
);

</script>
</body>
</html>

当我添加评论时,它们不会显示在评论列表中。我将评论数组的长度记录到控制台,它永远不会改变。我做错了什么?

最佳答案

您需要这样做,因为您在 onSubmit 事件中使用了一个字符串。

<form className='commentForm' onSubmit={this.handleSubmit}>

您的示例代码中有这个:

<form className='commentForm' onSubmit='handleSubmit'>

您的代码导致了 Uncaught TypeError: string is not a function 错误。由于该错误,它没有命中 handleSubmit 函数,还导致浏览器重新加载。

关于javascript - react .js : data not getting populated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21639255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com