gpt4 book ai didi

javascript - React 未在工作代码中定义

转载 作者:行者123 更新时间:2023-11-28 10:44:03 25 4
gpt4 key购买 nike

这段代码是我的同学写的,当我在他的网页上检查它时,它完美地工作了。当我将其复制到我的页面时,我得到的都是这些错误

enter image description here

TodoList 组件(制作项目列表,我从输入中获取的内容)

class TodoList extends React.Component{

// render this component
render() {
var items = this.props.items.map(function(item, index) {
return (
<li key={index}>
<span>{item} </span>
<img className="delete"
src="delete.jpg"
onClick={this.props.removeItem.bind(this, index)} />
</li>
);
}.bind(this));
return (
<ul>{items}</ul>
)
}

}

TodoForm 组件(为表单和表单本身制作 hadleSubmit)

class TodoForm extends React.Component{
// init component state
state = {
item: ""
}
// add a new item -> call parent
handleSubmit = (e) => {
// prevent normal submit event
e.preventDefault();
// call parent to add a new item
this.props.onFormSubmit(this.state.item);
// remove new typed item from text input
e.target.children[0].value = "";
// focus text input
e.target.children[0].focus();

}

// item value is changed
onChange = (e) => {
this.setState({item: e.target.value});
}

// render component
render(){
return (
<form onSubmit={this.handleSubmit}>
<input type="text" onChange={this.onChange} />
<input type="submit" value="Add" />
</form>
);
}

}

App组件(写入item的添加、删除)

class App extends React.Component {

// init component state
state = {
items: []
}

// add a new item
addItem = (newItem) => {
// returns a new list with a new item
let newArr = this.state.items.concat(newItem);
// render again
this.setState({items: newArr});
}

// remove item
removeItem = (index) => {

// remove from items array
let newArr = this.state.items;
newArr.splice(index, 1);
// render again
this.setState({items: newArr});
}

// render component
render(){
return (
<div>
<TodoForm onFormSubmit={this.addItem} />
<TodoList items={this.state.items} removeItem={this.removeItem} />
</div>
)
}

}

ReactDOM.render(
<App/>,
document.getElementById('root')
);

html 是(这是我的老师给的,他告诉这不应该改变)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Todo Example with React</title>
<link href="https://fonts.googleapis.com/css?family=Oswald" rel="stylesheet">
<link href="app.css" rel="stylesheet">
<script src="https://unpkg.com/react@latest/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@latest/dist/react-dom.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel" src="app.js"></script>
</body>

最佳答案

您使用的链接不会访问React的任何部分,无法为您提供React环境并运行代码。如果您使用

创建 react 应用程序,这对您来说会更好
npm install -g create-react-app
create-react-app app_name
npm start

然后将您的 React 组件添加到该应用程序中并轻松运行您的应用程序。

关于javascript - React 未在工作代码中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46735705/

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