直接贴代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/babel">
// class Timer extends React.Component {
// constructor(props) {
// super(props);
// this.state = { seconds: 0 };
// }
//
// tick() {
// this.setState(state => ({
// seconds: state.seconds + 1
// }));
// }
// // 组件加载
// componentDidMount() {
// this.interval = setInterval(() => this.tick(), 1000);
// }
// // 组件销毁
// componentWillUnmount() {
// clearInterval(this.interval);
// }
//
// render() {
// return (
// <div>
// Seconds: {this.state.seconds}
// </div>
// );
// }
// }
class ToDo extends React.Component {
constructor(props) {
super(props);
this.state = {
toDoList: [],
text: '',
countId: 0
}
this.handleSubmit = this.handleSubmit.bind(this)
}
render () {
return (
<div>
<h4>Do</h4>
<ToDoListCom toDoList = { this.state.toDoList } callback= { this.callbacktest } />
<form onSubmit= { this.handleSubmit }>
<input type="text" value= { this.state.text } onChange= { this.handleChange } />
<div>
<button>
Add + 1
</button>
</div>
</form>
</div>
)
}
// input 提交
handleSubmit (e) {
e.preventDefault()
if ( this.state.text != '' )
// setState 异步执行
this.setState(state => {
return {
toDoList: state.toDoList.concat({
text: state.text,
id: new Date().getTime()
}),
text: ''
}
})
}
// input change事件
handleChange = (e) => {
e.preventDefault()
this.setState({ text: e.target.value })
}
callbacktest = (data) => {
let toDoList = this.state.toDoList
toDoList.splice( data.index, 1 )
this.setState(() => {
return {
toDoList: toDoList
}
})
}
}
const styleReg = { flex: 1 , marginLeft: 12 + 'px' }
const elJsx = <h1> JSX </h1>
class ToDoListCom extends React.Component {
constructor(props) {
super(props)
this.state = {
flag: -1
}
}
render () {
return (
<ul>
{this.props.toDoList.map( (item, index) => (
<li key = { item.id } >
<div style={{ display: 'flex' }}>
<div onClick= { () => this.changeColor(item.id) } style= { this.state.flag === item.id ? this.addColor() : {} } >
{ item.text + item.id } { elJsx }
</div>
<div style={ styleReg }>
<button onClick={ () => this.deleteItem(item, index) }>
del
</button>
</div>
</div>
</li>
))}
</ul>
)
}
deleteItem = (item, index) => {
if (this.props.toDoList.length == 1)
console.log('the end !')
let params = {
item: item,
index: index
}
this.props.callback( params )
}
// 高亮
addColor = () => {
return { color: 'blue' }
}
changeColor = (id) => {
this.setState({
flag: id
})
}
}
ReactDOM.render (
<ToDo />,
document.getElementById('example')
)
</script>
</body>
</html>