react-路留言板(封装组件button)
在index.js
import React from 'react'
import ReactDom from 'react-dom'
import ToDoList from './components/ToDoList'
// import './assets/css/base.css';//全局引入 优化
ReactDom.render(
<ToDoList title="bmw" />,
document.querySelector('#app'),
()=>console.log('render is over!!!')
);
在todolist
import React from "react";
import UcButton from "./UcButton";
class ToDoList extends React.Component{
constructor(props){
super(props);
this.state={ //响应式
name:'',
content:'',
list:[
// {id:1,name:'alex',content:'alex123'}
]
};
}
// timer = null;//非响应式
send = () => {
this.setState({
list:this.state.list.concat({
id:this.state.list.length+1,
name:this.state.name,
content:this.state.content
}),
name:'',
content:''
})
};
del = (index,id) => {
//利用id -》 兜库->res success ↓
this.state.list.splice(index, 1);
this.setState({list:this.state.list})
};
check = (index,id) => {
this.state.list[index].content='bmw';
this.setState({list:this.state.list})
};
clear = () => {
this.setState({list:[]})
};
changeIpt = (ev) => {
this.setState({[ev.target.name]:ev.target.value})
}
render(){
let {list,name,content} = this.state
return (
<div>
<h3>留言板</h3>
<input
type="text"
value={name}
name="name"
onChange={this.changeIpt}
/>
<br/>
<input
type="text"
value={content}
name="content"
onChange={this.changeIpt}
/>
<br/>
<UcButton text="提交交" clickHandler={this.send} />
<br/>
<ul>
{
list.map((item,index)=>(
<li key={item.id}>
<span>{item.content}</span>
---
<em>{item.name}</em>
---
<a href="javascript:;" onClick={this.del.bind(null,index,item.id)}>删除</a>
<a href="javascript:;" onClick={()=>this.check(index,item.id)}>修改</a>
</li>
))
}
</ul>
{
this.state.list.length !== 0
&&
<UcButton text={'清空情况'} clickHandler={this.clear} mode="warning" />
}
</div>
)
}
}
export default ToDoList
在button内
import React,{Component} from 'react';
import propTypes from 'prop-types'
import './assets/css3/uc-button.css';//全局
class UcButton extends Component{
render(){
return (
<input
// className="s1 s2"
className={`s2 button--` + this.props.mode}
type="button"
value={this.props.text}
onClick={this.props.clickHandler}
/>
)
}
}
UcButton.defaultProps = {
text:'按钮',
mode:'primary'
};
UcButton.propTypes = {
text:propTypes.string,
mode:propTypes.string,
clickHandler: propTypes.func.isRequired
};
export default UcButton
在css内
.s1{
background: red;
}
.s2{
border: 1px slategray solid;
}
.button--primary{
background: cornflowerblue;
}
.button--warning{
background: bisque;
}