美文网首页
几个React+mobx入门练习--饭叔的前端零基础入门教程 (

几个React+mobx入门练习--饭叔的前端零基础入门教程 (

作者: 方健 | 来源:发表于2017-07-03 14:02 被阅读95次
  1. 用mobx改变组件状态
    有三个按钮和一个DIV,点击按钮后在DIV中显示对应的文字。
    点击“悟空”按钮后
    ![点击“悟净”按钮后](https://img.haomeiwen.com/i45703/f41d14c269bcce60.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240
@observer
export default class Ex1 extends React.Component<IEx1, {}> {
    render() {
        const store = this.props.store;
        return (<div>
            <button className={styles.mybutton} onClick={()=>store.setName("悟空")}>悟空</button>
            <button className={styles.mybutton} onClick={()=>store.setName("悟净")}>悟净</button>
            <button className={styles.mybutton} onClick={()=>store.setName("悟能")}>悟能</button>
            <div className={styles.content}>{store.name}</div>
        </div>)
    }
}
  1. 在父组件中用Prop控制子组件是否显示
    构造组件<People/>,含有3个子组件<Wukong/> <Wujing/> <Wuneng/>
    (图片来源:https://www.poocg.com/cynthiaxing
    <Wukong/>
    <Wujing/>
    <Wuneng/>
    <People name="悟空"/> 展示 <Wukong/>
    <People name="悟净"/> 展示 <Wujing/>
    <People name="悟能"/> 展示 <Wuneng/>
    例如:
    <People name="悟空"/>
@observer
export default class People extends React.Component<IPeople, {}> {
    static defaultProps: IPeople = {
        name:"悟空"
    };
    render() {
        const Comps={
            "悟空":Wukong,
            "悟能":Wuneng,
            "悟净":Wujing
        };
        const {name}=this.props;
        const NullComp=()=>null;
        const Comp=Comps[name]||NullComp;
        return (<Comp/>)
    }
}
  1. 在父组件中用Prop控制子组件的样式
    构造组件<ColorBox/>,是一个100px * 100px的方块,方块的背景色由color决定,中间显示颜色值
    如:
    <ColorBox color="#D5E8D4"/>


    ex3.png

    <ColorBox color="#FFF2CC"/>


    ex3_2.png
interface IColorBox {
    color: string
}
@observer
export default class ColorBox extends React.Component<IColorBox, {}> {
    static defaultProps: IColorBox = {
        color:"blue"
    };
    render() {
        const color = this.props.color;
        const style={
            width:100,
            height:100,
            textAlign:"center",
            backgroundColor:color
        };
        return (<div style={style}>{color}</div>)
    }
}

4.综合运用
以按钮切换图片显示


以按钮切换图片显示

相关文章

网友评论

      本文标题:几个React+mobx入门练习--饭叔的前端零基础入门教程 (

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