reactjs前端实践|第三篇:TodoList示例事件、state、props、refs

实践三

Todo List示例,未使用redux。内容涉及到展示组件与容器组件的合理使用,事件处理,参数传递,控件访问,组件功能设计等方面。其中遇到的坎,设置输入焦点,由于使用了styled-components而有不同;每个组件应试包含哪些state,是否应该进行状态提升;子组件如何向父组件传递数据。

代码分析

组件拆分:Li单个信息条目、LiList信息条目列表、InputAndButton输入组件、App容器组件。App的State包含一个item数组,存放信息列表;InputAndButton的State包含一个inputValue变量,存入用户本次输入的信息。其它组件不含State,为展示组件。

展示组件

Li.js,展示一条信息,数据来自父组件

const Li = (props) => {
    return (                           
        <TodoLi>{props.text}</TodoLi>              //此处不能加key(但父组件要向它传递),否则会有警告
    );
};
export default Li;

LiList.js,展示信息列表,因为输入组件也会修改数据,所以state提升到容器组件中。

const LiList = (props)=>{
    return (
        <TodoUl>
            {props.items.map((item)=>{             //map方法来完成列表构建
                return <Li {...item}></Li>;        //item中要包含一个key字段,否则会有警告
            })}
        </TodoUl>
    );
};
export default LiList;

输入组件

输入组件自己控制输入框的数据显示及清除,开始我把一切事件处理全放到App中了,这样方便了数据传递,但破坏了输入组件的内聚性。正确的方式是:输入组件自己控制界面的显示,只有在回车键按下或鼠标点击add按钮时,才将输入框中的数据传递给父组件(App)。

InputAndButton.js

class InputAndButton extends Component {
    constructor(props)    {
        super(props);
        this.state={
            inputValue:''                      //用来处理鼠标点击时取得输入数据
        };
    }
    onChange = e => {
        this.setState({
            inputValue:e.target.value         //按键时保存输入数据
        })
    };
    addItem = e => {
        if(e.which === 13 || e.type === 'click'){    //回车或鼠标点击
            if(this.state.inputValue.trim().length > 0) {     //输入不为空
                this.props.onSave(this.state.inputValue.trim());   //调用父组件提供的函数,向父组件传递数据。
                e.target.value = '';     //清空输入
                this.setState({          
                    inputValue:''
                })
            }
        }
    };
    render = () => {
        return (
            <div>
                <TodoInput onChange={this.onChange}
                           onKeyUp={this.addItem}
                           placeholder="enter task"
                           value={this.state.inputValue}>
                </TodoInput>
                <TodoButton onClick={this.addItem} type="submit">add</TodoButton>
            </div>
        );
    }
}
export default InputAndButton;

容器组件

class App extends Component {
    constructor(props){
        super(props);
        this.state={
            items:[]                   //信息列表数据
        };
    }
    handleSave(text){                 //传递到子组件的函数,接收数据并追加条目
        if(text.length !== 0){
            this.state.items.push({key: new Date().getTime(), text});     //key设定唯一值,不作说明,网上资料很多
            this.setState({
                items: this.state.items,
            })
        }
    };
    render() {
        return (
            <div>
                <InputAndButton onSave={this.handleSave.bind(this)}/>                     //处理函数以props传给子组件
                <LiList items={this.state.items}/>
            </div>
        );
    };
}
export default App;

输入焦点控制

利用特殊的属性 Ref来访问子组件中的控件,并控制输入焦点,需要注意的是:styled-components对这个属性有些改变,要用innerRef来替代ref,不然拿到的是一个 StyledComponent包装的对象,而不是DOM结点。有疑问,去看其文档的Tips and tricks部分之Refs to DOM nodes。

App.js中输入组件修改如下:

<InputAndButton ref={comp => { this.InputComponent = comp; }} onSave={this.handleSave.bind(this)}/>

App.js中增加componentDidMount处理,在组件加载完成时设置输入焦点。

    componentDidMount (){
        this.InputComponent.focus();
    };

InputAndButton.js中修改input如下:

<TodoInput innerRef={el=> { this.el = el; }}   ...

InputAndButton.js中增加函数,供父组件中调用。

    focus = () => {
        this.el.focus();
    };

项目地址

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 todo_list_react
npm start

小结

这次实践,学会了事件,数据传递,组件划分,功能设计等基本方法,可以去折腾redux了。

    原文作者:zhoutk
    原文地址: https://segmentfault.com/a/1190000009223348
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞