1.使用bootstrap样式
npm install bootstrap --save
在入口index.js中引入样式
import ‘bootstrap/dist/cssbootstrap.min.css’
2.受控组件表单
export default class NameCard extends Component{
constructor(props){
super(props)
this.state={
value:''
}
this.handleChange=this.handleChange.bind(this)
this.handleSubmit=this.handleSubmit.bind(this)
}
handleChange(e){
this.setState({
value:e.target.value
})
}
handleSubmit(e){
alert(this.state.value)
e.preventDefault()
}
render(){
return(
<form className="p-5" onSubmit={this.handleSubmit}>
<div className="form-group">
<label>留言</label>
<input
type="text"
className="form-control"
value={this.state.value}
onChange={this.handleChange}
placeholder="输入留言内容"
/>
</div>
<button type="submit" className="btn btn-primary">留言</button>
</form>
)
}
}
非受控组件
handleSubmit(e){
alert(this.input.value)
console.log(this.input)
e.preventDefault()
}
render(){
return(
<form className="p-5" onSubmit={this.handleSubmit}>
<div className="form-group">
<label>留言</label>
<input
type="text"
className="form-control"
placeholder="输入留言内容"
ref={(input)=>this.input=input}
/>
</div>
<button type="submit" className="btn btn-primary">留言</button>
</form>
)
}
3.当我们需要一个全局的数据可以使用context
!!这里要注意,consum的组件要包含在provider组件里面
**context.js
import React from 'react'
const ThemContext=React.createContext()
export default ThemContext
**app.js
//引入context
import ThemContext from "../context/them-context";
render(){
return(
<ThemContext.Provider value={them}>
<form className="p-5" onSubmit={this.handleSubmit}>
<div className="form-group">
<label>留言</label>
<input
type="text"
className="form-control"
placeholder="输入留言内容"
ref={(input)=>this.input=input}
/>
</div>
<button type="submit" className="btn btn-primary">留言</button>
</form>
</ThemContext.Provider>
)
}
GetContext.js
import ThemContext from "../context/them-context";
class GetContext extends Component{
render(){
return(
<ThemContext.Consumer>
{
(them)=>{console.log(them)}
}
</ThemContext.Consumer>
)
}
}
生命周期狗子的参数