【发布时间】:2018-06-10 16:54:36
【问题描述】:
我是新手,我正在尝试使用 jquery 动态地将 li 添加到 ul。 在我的 li 里面,我有一个带有 onclick 方法的 sapn。当我单击跨度时,我希望触发特定方法,但我得到 - Uncaught ReferenceError: deleteMsg is not defined at HTMLSpanElement.onclick。我一直在寻找解决方案,但没有任何效果。我不明白这是什么问题......
这是我的代码:
class CoachPage extends React.Component {
constructor(props, context) {
super(props, context);
this.state={
val: []
}
}
handleSend(msg){
this.state.val.push(msg);
this.setState({val: []});
}
// get all data from db and put in the list
componentWillMount(){
fetch('http://localhost:3003/api/msgs/')
.then(function(res) {
return res.json();
}).then(function(data){
var msgs = [data];
msgs[0].map(function(msg){
console.log(msg.msgdata);
//Here i add the li's with a sapn and onclick method called "deleteMsg"
$('#coach-panel-content').append(
(`<li class=myli>${msg.msgdata}<span onclick=deleteMsg('${msg._id}')>X</span></li><hr>`));
})
})
.catch(function(error) {
console.log(error)
});
}
deleteMsg(item){
return fetch('http://localhost:3003/api/msgs/' + item, {
method: 'delete'
}).then(response =>
response.json().then(json => {
return json;
})
);
}
render() {
return (
<div className="container" style={{color: '#FFF', textAlign: 'right'}}>
<h1>Coach Page</h1>
<AddMsg onSend={this.handleSend.bind(this)} />
<Panel header="עדכונים" bsStyle="info" style={{float: 'left', textAlign: 'right', width: '40em'}}>
<ul id="coach-panel-content">
</ul>
</Panel>
</div>
);
}
}
export default CoachPage;
更新:
我进行了@sandor vasas 所说的所有更改,直到现在我才注意到,但是当我尝试添加新的 msg 时,我收到了这个错误:“Uncaught ReferenceError: val is not defined”。我不确定我明白为什么会发生这种情况.. 这是我更新的代码:
class CoachPage extends React.Component {
constructor(props, context) {
super(props, context);
this.state={
val: []
}
}
handleSend(msg){
this.state.val.push(msg);
this.setState({val});
}
// get all data from db and put in the list
componentDidMount(){
fetch('http://localhost:3003/api/msgs/')
.then( res => res.json() )
.then( data => this.setState({ val: data }))
.catch( console.error );
}
deleteMsg(item){
return fetch('http://localhost:3003/api/msgs/' + item, {
method: 'DELETE'
}).then(response =>
response.json()
.then(json => {
return json;
})
);
}
render() {
return (
<div className="container" style={{color: '#FFF', textAlign: 'right'}}>
<h1>Coach Page</h1>
<AddMsg onSend={this.handleSend.bind(this)}/>
<Panel header="עדכונים" bsStyle="info" style={{float: 'left', textAlign: 'right', width: '40em'}}>
<ul id="coach-panel-content">
{
this.state.val.map( (msg, index) =>
<li key={index} className='myli'>
{msg.msgdata}
<span onClick={() => this.deleteMsg(msg._id)}>X</span>
<hr/>
</li>
)
}
</ul>
</Panel>
</div>
);
}
}
export default CoachPage;
【问题讨论】:
标签: javascript jquery html reactjs fetch-api