美文网首页
5.组件数据挂载props及prop-types

5.组件数据挂载props及prop-types

作者: __疯子__ | 来源:发表于2020-05-20 14:16 被阅读0次

教程1-14完整项目地址 https://github.com/x1141300029/react-Todos.git

1.props
​ 1.1.方式1:

src/App.js

<Fragment>
    <TodoHeader desc="今日事,今日毕。">待办事项</TodoHeader>  #update
    <TodoInput/>
    <TodoList/>
</Fragment>

src/components/TodoHeader/index.js 部分代码

export default function TodoHeader(props){ #update
    //接收参数
    console.log(props); #insert
    return (
      <> #insert 
        <h1>{props.children}</h1>  #update
            <h3>{props.desc}</h3>
      </> #insert
    )
};

​ 1.2.方式2:

src/App.js

<Fragment>
    <TodoHeader desc="今日事,今日毕。">待办事项</TodoHeader>
    <TodoInput btnText="ADD"/> #update
    <TodoList/>
</Fragment>

src/components/TodoInput/index.js

class TodoInput extends Component {
    render() {
        return (
            <div>
                <input type="text"/><button>{this.props.btnText}</button> #update
            </div>
        );
    }
}

2.参数格式检查prop-types

https://www.npmjs.com/package/prop-types
cnpm i -D prop-types

​ 2.1.函数组件 src/components/TodoHeader/index.js

import React, {Component} from 'react';
import PropTypes from 'prop-types' #insert

export default function TodoHeader(props){
    //接收参数
    console.log(props);
    return (
        <>
            <h1>{props.children}</h1>
            <h3>{props.desc}</h3>
        </>

    )
};
/**                                        
 * 检查props中的数据类型                     
 */                                        
TodoHeader.propTypes={                     #insert
    desc:PropTypes.string.isRequired       #insert
}                                          #insert
/**
 * 默认值
 */
TodoHeader.defaultProps={                  #insert
    desc:"默认"                             #insert
};                                         #insert

​ 2.2.类组件 src/components/TodoInput/index.js

import React, {Component} from 'react';
import PropTypes from 'prop-types'   #insert

class TodoInput extends Component {
    
    static propTypes={               #insert
        btnText:PropTypes.string     #insert
    };                               #insert
    //默认值
    static defaultProps = {          #insert
        btnText: "添加"               #insert
    };                               #insert

    render() {
        return (
            <div>
                <input type="text"/><button>{this.props.btnText}</button>
            </div>
        );
    }
}

export default TodoInput;

相关文章

网友评论

      本文标题:5.组件数据挂载props及prop-types

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