美文网首页
【总结】React开发常用

【总结】React开发常用

作者: giraffecode9668 | 来源:发表于2019-11-17 00:38 被阅读0次

    简介

    React是facebook公开的前端框架,vue是前google尤雨溪和他的小伙伴的开源项目,加上angular,三者是前端流行的三大主流框架
    一般而言,他们的学习入门难度:angular > react > vue

    因为项目使用的是react,所以学习了react的相关知识,整理总结总结

    react 定义

    • 元素定义:const ele = (<b>你好</b>)

    • ReactDom给结点赋值元素函数(一般用在dom)

    ReactDOM.render(
        element,
        document.getElementById('example')
    );
    

    定义组件(两种):

    function HelloMessage(props) {
        return <h1>Hello World!</h1>;
    }
    
    class Welcome extends React.Component {
      render() {
        return <h1>Hello World!</h1>;
      }
    }
    

    react 生命周期

    生命周期是react的特点,网上有许多的讲解,我就只简单讲讲在开发中的应用:

    • constructor(props): 构造函数,在初始组件的时候调用,即最开始调用,一般可以这么写:constructor(props) { super(props); this.state = {}; }

    • componentDidMount():在组件第一次渲染完成后调用,可以在这个方法调用接口,使用setState({})方法来通知刷新组件

    • componentWillReceiveProps(nextProps):父组件向子组件更新props值是调用该方法,nextProps是新值

    • render():是组件渲染的调用

    以上几个应付开发基本足够了,其他有需要可以搜搜资料

    传值(重点)

    1. 父组件向子组件传值
    /**
     * 父组件,向子组件传递父组件的属性
     * categorys,parentId属性值
     * setForm 属性方法
     */
    <AddForm 
        categorys={categorys} 
        parentId={parentId} />
    
    // 子组件获得父组件的值
    construtor(props){
      super(props)
      this.state({
          categorys: this.props.categorys
      })
    }
    
    1. 子组件调用父组件的方法(子组件调用父组件方法可以获得父组件值)
    <AddForm 
        setForm={(form) => { this.form = form }} />
    
    // 子组件调用父组件方法
    componentWillMount(){
            this.props.setForm(this.props.form)
        }
    
    1. 父组件获得子组件的值(可以通过ref容器调用子组件方法获得子组件值)
    /**
     * 父组件
     */
    constructor(props) {
            super(props)
    
            // 创建容器
            this.pw = React.createRef()
            this.editor = React.createRef()
        }
    
    
    const imgs = this.pw.current.getDetail ()
    
    
    render(){
      return <Son ref={pw}/>
    }
    
    /**
     * Son 子组件
     */
    getDetail = () => {
        // 返回对应数据的html格式文本
        return draftToHtml(convertToRaw(this.state.editorState.getCurrentContent()))
    }
    

    相关文章

      网友评论

          本文标题:【总结】React开发常用

          本文链接:https://www.haomeiwen.com/subject/lrzbhctx.html