reactjs前端实践|第一篇:调色板示例组件的使用
背景
原因
技术栈
工具
在学习、开发阶段,有它真好。我发现,拖了这久我才行动起来,原来是我没有遇见create-react-app这个神器啊,呵呵。 实践一
示例描述显示一块调色板,上面一个正方形展现真实颜色,下面一个文字标签显示颜色的16进制编码,色值由父类单入口传递。 代码结构整个App分解为三个组件,一个父组件(Card)、两个子组件(Square、Label),颜色值由Card组件的Props向子组件单向传递,样式使用styled-components来定义。 代码分析父组件(Card) import React,{ Component } from 'react'; import styled from 'styled-components'; import Square from './Square'; import Label from './Label'; const CardDiv = styled.div` //定义卡片div height: 200px; width: 150px; padding: 0,background-color: #FFF; -webkit-filter: drop-shadow(0px 0px 5px #666); //这行可以删除 filter: drop-shadow(0px 0px 5px #666); `; class Card extends Component { render() { return ( <CardDiv> <Square color={this.props.color}/> //传递Props <Label color={this.props.color}/> </CardDiv> ); } } export default Card; 子组件(Square) import React,{ Component } from 'react'; import styled from 'styled-components'; const SquareDiv = styled.div` height: 150px; background-color: ${props => props.color}; //styled-components中接收父组件传递来的参数的方式 `; class Square extends Component { render() { return ( <SquareDiv {...this.props}></SquareDiv> //延展符的使用,传递属性到styled-components中 ); } } export default Square; 子组件(Label) import React,{ Component } from 'react'; import styled from 'styled-components'; const P = styled.p` font-family: sans-serif; font-weight: bold; padding: 13px; margin: 0; `; class Label extends Component { render() { return ( <P>{this.props.color}</P> ); } } export default Label; 组件加载(index.js) import Card from './components/Card'; ReactDOM.render( <Card color="#FFA737"/>,document.getElementById('root') ); 项目地址https://git.oschina.net/zhoutk/reactodo.git https://github.com/zhoutk/reactodo.git 使用方法git clone https://git.oschina.net/zhoutk/reactodo.git or git clone https://github.com/zhoutk/reactodo.git cd reactodo npm i git checkout color-card npm start 小结这是第一篇,主要是技术选型思考,样式的处理思考了很久,最后决定用style-components,希望它不要让我失望。难点:父组件的属性传递到styled-components组件中的方式,它以子组件的方式来组织的,并采用了回调函数的方式,与JSX的直接使用方式有所不同,试验了好多次,才理解。后来想想,还是本人对前端的思维不熟练导致的,要加强实践,加油! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |