React基础知识(一)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_41805715/article/details/99685176

一、React介绍

是一个开源(为数据渲染视图)的js库
virtualDOM、单向数据流来解决视图更新频繁的问题。

使用场景:
数据大量变化 视图更新频繁,(简单的页面不建议应用react)

React特点:
1.声明式设计:采用声明式,轻松描述应用
2.JSX:JavaScriptXml语法,是js的扩展
3.组件:构建组件,提高复用率,降低测试难度,提高开发速度
4.单向数据流
5.高效、灵活
不支持IE8以下的浏览器

环境搭建
1.引入react相关文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <!-- 生产环境中不建议使用 -->
    <script src="https://unpkg.com/[email protected]/babel.min.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/babel">
    ReactDOM.render(
        <h1>Hello React</h1>,
        document.getElementById("example")
    )
</script>
</body>
</html>

render方法:是React的最基本的方法,用于将第一个参数所对应的标签转换为html语言,插入到指定的DOM节点
jsx语法需要设置type=‘text/babel’

jsx语法:
如果遇到<,就会使用html解析
如果遇到{,就会使用js去解析

<script type="text/babel">
    ReactDOM.render(
        <div>{3+4}</div>,
        document.getElementById("example")
    )
</script>

组件:

<script type="text/babel">
    function HelloMessage(props) {
    return (<div>
        <h1>Hello {props.name}!</h1>
        <h2>It is ok!</h2>
    </div>)
    ReactDOM.render(
        <HelloMessage name="component"/>,
        document.getElementById("example")
    )
</script>

prop(值的传递-->单向数据流)
指定属性
在线babel编译器:http://babeljs.io/repl
React.Children用法:

class MyList extends React.Component {
    render () {
        return <ol>
            {
                React.Children.map(this.props.children,function (child) {
                    return <li>{child}</li>
                })
            }
        </ol>
    }
}
ReactDOM.render(
    <MyList>
        <span>test01</span>
        <span>test02</span>
        <span>test03</span>
    </MyList>,
    document.getElementById("example")
)

虚拟DOM(Virtual DOM)(ref–>组件中找到真实的元素)
是一种数据结构,各种各样的组件。当页面被渲染,就插入真实DOM。
更新了数据,vDOM结合diff的算法,遍历对比与真实DOM,不同的更新到真实DOM中。
通过组件获取真实的DOM节点,可以通过ref属性去实现。指定ref:<组件 ref='名称'>
通过读取ref对象的属性值拿到:this.refs.名称

class MyComponent extends React.Component{
    handleClick(){
        console.log(Number(this.refs.inputA.value)+Number(this.refs.inputB.value));
    }
    render(){
        return (
            <div>
                <input type="text" ref="inputA"/>+
                <input type="text" ref="inputB"/>
                <button onClick={this.handleClick.bind(this)}>click</button>
            </div>
        )
    }
}

ReactDOM.render(
    <MyComponent/>,
    document.getElementById("example")
)

VDOM的工作方式:
1.创建的各个组件就是虚拟DOM,存在内存
2.需要更新视图时,React会通过diff的算法对比虚拟DOM和真实DOM
3.找到最优方案:更新DOM的成本最低的方法
4.更新
组件间传递

class ButtonCompontent extends React.Component{
    handlerClick(){
        this.props.funcDeal();
    }
    render(){
        return <div>
            <button onClick={this.handlerClick.bind(this)}>click</button>
        </div>
    }
}
class MainCompontent extends React.Component{
    handleClick(){
        console.log("下单");
    }
    render(){
        return <ButtonCompontent funcDeal={this.handleClick.bind(this)}/>
    }
}
ReactDOM.render(
    <MainCompontent/>,
    document.getElementById("example")
)

组件间通信:

class AComponent extends React.Component{
    handlerChange(){
        this.props.funcSave(this.refs.inputTxt.value);
    }
    render(){
        return <input type="text" ref="inputTxt" onChange={this.handlerChange.bind(this)}/>
    }
}
class BComponent extends React.Component{
    handleClick(){
        console.log(this.props.funcDeal());
    }
    render(){
        return <button onClick={this.handleClick.bind(this)}>{this.props.name}</button>
    }
}
class MainComponent extends React.Component{
    result=0;
    save(value){
        this.result=value;
    }
    get(){
        return this.result;
    }
    render(){
        return <div>
            <AComponent funcSave={this.save.bind(this)}/>
            <BComponent name="获取" funcDeal={this.get.bind(this)}/>
        </div>
    }

}
ReactDOM.render(
    <MainComponent/>,
    document.getElementById("example")
)

state状态:
只要更新state,就会根据state重新渲染用户界面,react来处理如何最高效的更新DOM
设置状态:setState修改状态
读取状态:this.state.状态名称

class Clock extends React.Component {
    constructor(props) {
        super(props);
        this.state = {switch: false};
    }
    tick() {
        this.setState({
            switch: !this.state.switch
        });
    }

    render() {
        return (
            <div>
                <button onClick={this.tick.bind(this)}>{"当前状态:"+this.state.switch} </button>
            </div>
        );
    }
}
ReactDOM.render(<Clock />, document.getElementById('example'));

二、React组件的生命周期

生命周期的3个阶段
mount插入到DOM
update重新渲染
unmount从DOM移除
生命周期方法:
componentWillMount()准备插入
componentDidMount()已经插入

componentWillReceiveProps 在组件接收到一个新的 prop (更新后)时被调用。这个方法在初始化render时不会被调用。
shouldComponentUpdate 返回一个布尔值。在组件接收到新的props或者state时被调用。在初始化时或者使用forceUpdate时不被调用。
可以在你确认不需要更新组件时使用。

componentWillUpdate()准备更新
componentDidUpdate()已经更新

componentWillUnmount()准备从DOM中移除

class LeftCycle extends React.Component{
    constructor(props){
        super(props);
        this.state = {opacityValue : 0};
    }
    componentDidMount(){
        setInterval(()=>{
            var nowValue = this.state.opacityValue;
            nowValue += 0.1;
            if(nowValue > 1){
                nowValue = 0;
            }
            this.setState({opacityValue : nowValue},()=>{
                console.log(this.state.opacityValue);
            });
        },1000)
    }
    render(){
        return <div style={{opacity:this.state.opacityValue}}>盒子</div>
    }
}
ReactDOM.render(
    <LeftCycle />,
    document.getElementById("example")
)

三、事件

将React组件中的方法分为两大类
1.React自有的方法:生命周期和render
2.用户自定义的方法,遵循驼峰式命名:handleChange handleClick(handle+eventName)
采用标准的事件对象。

四、表单元素

表单元素有以下的属性设置都是受控组件:
value(input)
checked(checkbox radio)
selected(option)

其余的都是非受控组件。

class  FormComponent extends React.Component{
    constructor(prop){
        super(prop);
        this.state={result:''};
    }
    handleChange(event){
        console.log(event.target.value);
        this.setState({result: event.target.value})
    }
    handleSubmit(event){
        event.preventDefault();
        console.log(this.state.result)
    }
    render() {
        return (
            <div>
                <form onSubmit={this.handleSubmit.bind(this)}>
                    <input type="text" onChange={this.handleChange.bind(this)} value={this.state.result}/>
                    <input type="submit" value="提交"/>
                </form>
            </div>
        );
    }
}
ReactDOM.render(
    <FormComponent/>,
    document.getElementById("example")
)

猜你喜欢

转载自blog.csdn.net/qq_41805715/article/details/99685176