zoukankan      html  css  js  c++  java
  • react 组件传递

    状态提升:当两个以上组件使用同一个数据时,将数据提升到父组件中

    数据流向: 父组件传递到子组件中

    CommentList.js
    
    import React from 'react'
    const CommentList = ({comments})=>{
        return(
            <div className="comment-list">
                <label>评论列表</label>
                <ul className="list-group mb-3">
                    {
                        comments.map((comment, index) => 
                            <li key={index} className="list-group-item">{comment}</li>
                        )
                    }
                </ul>
            </div>
        )
    }
    export default CommentList
    CommentBox.js
    
    import React from 'react';
    class CommentBox extends React.Component{
        constructor(props){
            super(props)
            this.submitHandle = this.submitHandle.bind(this)
        }
        submitHandle(event){ this.props.onAddComment(this.textInput.value);
            event.preventDefault();
        }
        render() {
            return(
                <form className="p-5" onSubmit={this.submitHandle}>
                    <div className="form-group">
                        <label>留言:</label>
                        <input ref={ (textInput) => {this.textInput = textInput}}
                            type="text" 
                            className="form-control" 
                            >
                        </input>
                    </div>
                    
                    <button type="submit" className="btn btn-primary">提交</button>
                    <p>已有{this.props.commentsLength}条评论</p>
                </form>
            )
        }
    }
    export default CommentBox
    App.js
    import CommentBox
    from './component/CommentBox2' import CommentList from './component/CommentList' class App extends Component{ constructor(props){ super(props); this.state = { comments: ["this is the first comment","this is the first comment"] } this.addComment = this.addComment.bind(this) } addComment(comment){ this.setState({ comments: [...this.state.comments, comment] }) } render(){ const { comments } = this.state; return( <div className="App"> <header className="App-header"> <CommentList comments={comments}></CommentList> <CommentBox commentsLength={comments.length} onAddComment = {this.addComment} ></CommentBox> </header> </div> ) } } export default App;
  • 相关阅读:
    Python异常处理
    python抽象类
    python传参*和**的区别
    python 多重继承构造函数调用顺序
    linux 自启动 | 三种方式自启动
    Linux 项目 shell 自动获取报告本机IP (1) | 通过shell 自动获取报告本机IP
    Go 基础学习笔记 (5)| 数据类型说明与使用
    GO 基础学习笔记(4)| 参数传递
    生活问题 | 对华为畅玩手机5X进行升级
    markdown 语法
  • 原文地址:https://www.cnblogs.com/150536FBB/p/13906789.html
Copyright © 2011-2022 走看看