本文主要是介绍storybook 用react写组件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
storybook 用react写组件
笔者也是最近两天才开始接触的React和storybook,初步学习了组件部分的知识。在学习的时候也查阅过不少文章,对新手来说,有些确实看得不太懂,所以写下这篇文章。
继上一篇文章简单使用React写组件放到storybook中,现在要讲一下如何自己创建组件并放在storybook中,可能语言表达不是很精确,请见谅。
- 在项目中的src文件夹下新建一个components文件夹,用来存放自己写的组件文件,此处照书上敲了个登录组件,取名为login.js。
import React from 'react'export class Login extends React.Component{ //export提供一个对外接口,方便被其他部分引用constructor(props){super(props);this.login=this.login.bind(this);this.check=this.check.bind(this);this.state={userName:"admin",password:"admin"}}login(){if(this.refs.user.value===this.state.userName&&this.refs.pwd.value===this.state.password)alert("登陆成功");elsealert("登陆失败");}check(){if(this.refs.user.value.length>10)alert("超出10个字符,请重新输入");}render(){var loginStyle={width:400,height:250,background:"#FFF",margin:"200px auto",position:"relative"};var hStyle={position:"absolute",left:95,top:-40,padding:0,margin:50};var pStyle={textAlign:"center"};var userStyle={width:200,height:30,border:"solid #ccc 1px",borderRadius:3,paddingLeft:32,marginTop:50,};var pwdStyle={width:200,height:30,border:"solid #ccc 1px",borderRadius:3,paddingLeft:32,marginTop:5,};var buttonStyle={width:232,height:30,background:"#E9E9E9",border:"solid #ccc 1px",borderRadius:3,textAlign:"center"};return(<div style={loginStyle}><h1 style={hStyle}>登录界面</h1><div><p style={pStyle}><input type="text" style={userStyle} placeholder="用户名" ref="user" onChange={this.check}/></p><p style={pStyle}><input type="password" style={pwdStyle} placeholder="密码" ref="pwd"/></p><p style={pStyle}><button style={buttonStyle} onClick={this.login}>登录</button></p></div></div>)}
}
- 上一篇文章中新建了一个stories文件夹,里面有一个index.js文件,在里面引入这个登录组件
import { Login } from '../src/components/login'; //这一句是引入我们编写的组件
storiesOf('Login',module).add('login',()=>(<Login />));
- 大功告成,接下来
npm run storybook
就可以看到效果了
在这里要说一下第二步引入组件的时候,如果是这么写的:
storiesOf('Button', module).add('with text', () => ( // 一个 add 表示添加一个 story<Button>Hello Button</Button>)).add('with some emoji', () => ( // 这里是另一个 story<Button><span role="img" aria-label="so cool">😀 😎 👍 💯</span></Button>))
storiesOf('Login',module).add('login',()=>(<Login />));
那么效果就是这样子的:
如果是这么写的:
storiesOf('Button', module).add('with text', () => ( // 一个 add 表示添加一个 story<Button>Hello Button</Button>)).add('with some emoji', () => ( // 这里是另一个 story<Button><span role="img" aria-label="so cool">😀 😎 👍 💯</span></Button>)).add('login',()=>(<Login />));
效果就是这样子的:
看出两者的区别了吗?
这篇关于storybook 用react写组件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!