萌新react第一步:基础使用
程序员文章站
2022-03-16 14:15:51
...
写在开头
// vscode React 模块快捷创建
// 左上角文件->首选项->用户片段
{
"Snippet Name": {
"prefix": "myReact", // 触发片段的快捷键
"body": [
"import React, { $1 } from 'react'",
"",
"class $2 extends ${1} {",
" render(){",
" return (",
" <div>"
" $3$0",
" </div>"
" )",
" }",
"}",
"",
"export default ${2:MyComponent}"
],
"description": "Create Basic Component"
},
"Constructor": {
"prefix": 'ctr',
"body": [
"constructor() {",
" super()",
"}"
]
}
}
state
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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="demo"></div>
<script type="text/babel">
// 1.定义组件
class Like extends React.Component {
constructor(props) {
super(props)
// 初始化state
this.state = {
isLike: false
}
}
// 新添加方法:内部的this默认不是组件对象,而是undefined
handleClick = () =>{
// 得到状态
const isLike = !this.state.isLike
// 更新状态
this.setState({isLike})
}
// 重写组件类的方法
render() {
// 读取状态
const { isLike } = this.state
return <h2 onClick={this.handleClick}>{isLike ? 'kirito' : 'asuna'} </h2>
}
}
// 2.渲染组件标签
ReactDOM.render( < Like/ > , document.getElementById('demo'))
</script>
</body>
</html>
var foo = 'bar';
props
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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>
<script src="https://unpkg.com/[email protected]/prop-types.js"></script>
</head>
<body>
<div id="demo"></div>
<div id="demo2"></div>
<script type="text/babel">
// 1.定义组件
// function Persion(props) {
// return (
// <ul>
// <li>姓名: {props.name}</li>
// <li>年龄: {props.age}</li>
// <li>性别: {props.sex}</li>
// </ul>
// )
// }
class Persion extends React.Component{
render(){
return (
<ul>
<li>姓名: {this.props.name}</li>
<li>年龄: {this.props.age}</li>
<li>性别: {this.props.sex}</li>
</ul>
)
}
}
// 指定属性默认值
Persion.defaultProps = {
sex: '女',
age: 15
}
// 指定属性类型和必要性
Persion.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number
}
// 2.渲染组件标签
const p1 = {
name:'kirito',
age:16,
sex: '男'
}
// ReactDOM.render( < Persion name={p1.name} age={p1.age} sex={p1.sex}></ Persion> , document.getElementById('demo'))
ReactDOM.render( < Persion {...p1}></ Persion> , document.getElementById('demo'))
const p2 = {
name:'asuna',
}
ReactDOM.render( < Persion name={p2.name}></ Persion> , document.getElementById('demo2'))
</script>
</body>
</html>
定义组件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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>
<script src="https://unpkg.com/[email protected]/prop-types.js"></script>
</head>
<body>
<div id="demo"></div>
<script type="text/babel">
// 定义组件
class MyComponent extends React.Component{
constructor(props){
super(props)
}
showInput = () => {
const input = this.refs.content
// alert(input.value)
alert(this.input.value)
}
handleBlur = (event) =>{
alert(event.target.value)
}
render(){
return (
<div>
<input ref="content" type="text"/>
<input ref={input=>this.input = input} type="text"/>
<button onClick={this.showInput}>提示输入数量</button>
<input type="text" placeholder="失去焦点提示数据" onBlur={this.handleBlur}/>
</div>
)
}
}
// 2.渲染组件标签
ReactDOM.render( < MyComponent></ MyComponent> , document.getElementById('demo'))
</script>
</body>
</html>
组件组合使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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>
<script src="https://unpkg.com/[email protected]/prop-types.js"></script>
</head>
<body>
<div id="demo"></div>
<script type="text/babel">
/*
如果所有子组件都需要,数据保存在最外层组件中
如果只有某个组件需要,放在对应组件中
子组件中不能直接改变父组件的状态
状态在哪个组件,更新状态的行为就应该定义在哪个组件
*/
class App extends React.Component{
constructor(props){
super(props)
// 初始化
this.state = {
todos: ['吃饭','睡觉','锻炼']
}
}
addTodo = (todo) => {
const {todos} = this.state
todos.unshift(todo)
this.setState({todos})
}
render(){
const {todos} = this.state
return (
<div>
<h1>Simple TODO List</h1>
<Add addTodo={this.addTodo} count={todos.length + 1}></Add>
<List todos={todos}></List>
</div>
)
}
}
class Add extends React.Component{
constructor(props){
super(props)
}
add = () =>{
// 读取输入的数据
const todo = this.todoInput.value.trim()
// 检查合法性
if (!todo) {
return
}
// 添加
this.props.addTodo(todo)
// 清除输入
this.todoInput.value = ''
}
render(){
return (
<div>
<input type="text" ref={input => this.todoInput = input} />
<button onClick={this.add}>add #{this.props.count}</button>
</div>
)
}
}
class List extends React.Component{
render(){
return (
<ul>
{
this.props.todos.map((todo,index)=>{
return <li key={index}>{todo}</li>
})
}
</ul>
)
}
}
Add.propTypes = {
count: PropTypes.number.isRequired,
addTodo: PropTypes.func.isRequired
}
List.propTypes = {
todos: PropTypes.array.isRequired
}
ReactDOM.render( <App></App> , document.getElementById('demo'))
</script>
</body>
</html>
表单提交
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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>
<script src="https://unpkg.com/[email protected]/prop-types.js"></script>
</head>
<body>
<div id="demo"></div>
<script type="text/babel">
class LoginForm extends React.Component{
constructor(props){
super(props)
this.state = {
pwd: ''
}
}
handleSubmit = (event) =>{
// 阻止事件默认行为
const name = this.nameInput.value
const {pwd} = this.state
alert(`${name},'------',${pwd}`)
event.preventDefault()
}
handleChange = (event) =>{
// 读取输入的值
const pwd = event.target.value
// 更新pwd的状态
this.setState({pwd})
}
render() {
return (
<form action="" onSubmit={this.handleSubmit}>
用户名: <input type="text" ref={input => this.nameInput = input} />
密码: <input type="password" value={this.state.pwd} onChange={this.handleChange} />
<input type="submit" value="登陆"/>
</form>
)
}
}
ReactDOM.render(<LoginForm></LoginForm>,document.getElementById('demo'))
</script>
</body>
</html>
生命周期
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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="demo"></div>
<script type="text/babel">
// 1.定义组件
class Life extends React.Component {
constructor(props){
super(props)
this.state = {
opacity: 1
}
}
// 组件挂载到页面时
componentDidMount(){
// 启动循环定时器
this.intervalId = setInterval(() => {
console.log('定时器执行');
let {opacity} = this.state
opacity -= 0.1
if (opacity <= 0) {
opacity = 1
}
this.setState({opacity})
}, 200);
}
distroyComponent = () => {
// 调用删除组件方法删除组件
ReactDOM.unmountComponentAtNode(document.getElementById('demo'))
}
// 组件将要被卸载时触发
componentWillUnmount(){
// 清理定时器
clearInterval(this.intervalId)
}
render() {
const {opacity} = this.state
return (
<div>
<h2 style={{'opacity': opacity}}>{this.props.msg}</h2>
<button onClick={this.distroyComponent}>嗝屁了</button>
</div>
)
}
}
ReactDOM.render( < Life msg="react恶心啊" / > , document.getElementById('demo'))
</script>
</body>
</html>
上一篇: SpringBoot 第三天——@RestController、@RequestMapping、@PathVariable、@RequestPaeam、@GetMapping的使用
下一篇: 自动拆装箱
推荐阅读