【问题标题】:Passing Function parameter to another component in react将函数参数传递给反应中的另一个组件
【发布时间】:2020-09-10 04:59:18
【问题描述】:

我学习反应并停留在这个地方。我正在创建一个应用程序,用户将在其中看到具有不同 ID 和名称的产品列表。我创建了另一个组件,产品的详细信息将在其中打开。我通过 onClick 函数在我的 addList 组件中收集特定产品的 id 和 value。现在我想在 DetailList 组件中发送这些值,以便我可以显示该特定产品的详细信息。

类似的路线图

添加列表->(用户单击产品)->产品的ID和名称传递给DetailList组件->通过获取产品详细信息打开详细列表组件。

这是我添加列表组件的代码


    export default class Addlist extends Component {
    constructor(props) {
      super(props)
      this.state = {
        posts : []
      }
    }
    
      passToDetailList(id) {
          console.log( id)
    }
    
      async componentDidMount() {
        axios.get('http://localhost:80/get_add_list.php')
            .then(response => {
              console.log(response);
              this.setState({posts: response.data})
            })
            .catch(error => {
              console.log(error); 
            })
        } 
        
        render() {
          const { posts } = this.state;
            //  JSON.parse(posts)
            return (
              <Fragment>
               <div className="container" id="listOfAdd">
                      
              <ul className="addUl">
            {
              posts.map(post => {
                return (
                <li key={post.id}>
                   <div className="row">
                    <div className="col-md-4">
                      <img src={trialImage}  alt=""></img>
                    </div> {/* min col  end */}
                    <div className="col-md-8">
                <b><h2>{post.add_title}</h2></b>
                      
                     

    {/* This button is clicked by user to view detail of that particular product */}
                        <button onClick={() => this.passToDetailList(post.id)}>VIEW</button>
    
                    </div> {/* min col  end */}
                  </div> {/* row end */}
                  
                  </li> 
                );
              })}
                      
     
             </ul>
           </div>{/* container end */}
       </Fragment>
            )
        }
    }

【问题讨论】:

    标签: javascript reactjs react-router jsx


    【解决方案1】:

    你应该通过路由传递数据 -

    <Route path="/details/:id" component={DetailList} /> // router config
    
    passToDetailList(id) {
         this.props.history.push('/details/'+id)
    }
    

    然后在 DetailList 组件中,可以通过 - 访问值

    console.log(this.props.match.params.id) - //here is the passed product Id 
    

    【讨论】:

    • 我将我的 id 作为函数的参数。由于我们不能在路径中使用反引号,所以我将如何在路径中传递该变量。
    • passToDetailList(id) { this.props.history.push('/details/'+id) } 导航时您可以传递 id
    • 你能告诉我是否有一种情况,如果我想按照这种方法发送姓名和身份证。这有效吗 path="/details/:id/:name
    • 是的,如果您想了解更多信息,请查看此链接:medium.com/better-programming/…
    【解决方案2】:

    您需要将idstate 提升为AddListDetailList 之间的共同父级,然后在父组件中创建一个函数来设置id 并传递id 和@987654328 @ 函数到你的 AddList 组件通过 props ,然后只需使用 setId 函数在 passToDetailList 函数中设置 id 状态。

    最后,您可以在 DetailList 组件中使用 id 来获取其详细信息

    下面是您的AddList 组件的外观:

    export default class Addlist extends Component {
      constructor(props) {
        super(props);
        this.state = {
          posts: []
        };
      }
    
      passToDetailList(id) {
        this.props.setId(id);
      }
    
      // The rest of your code
    }
    

    这是您的DetailList 组件的外观:

    export default class DetailList extends Component {
      componentDidMount(){
        // Use the id to fetch its details
        console.log(this.props.id)
      }
    }
    

    最后是你的CommonParent 组件:

    
    export default class CommonParent extends Component {
      constructor(props) {
        super(props);
        this.state = {
          id: ''
        };
        this.setId = this.setId.bind(this);
      }
    
      setId(id){
        this.setState({
          id
        })
      }
    
      render(){
        return(
          <>
            <AddList setId={this.setId} />
            <DetailList id={this.state.id} />
          </>
        )
      }
    }
    

    如果您的组件在组件树中彼此相距很远,您可以使用react contextredux 来处理id 状态

    【讨论】:

    • 能否请您分享我可以阅读更多有关此的链接。那会有很大帮助。同样在用户单击它的按钮后它会自动定向到 DetailList 组件。我将如何实现这一目标。我正在考虑使用 window.location 方法。在那种情况下我可以使用不同的东西吗?
    • 我以为你同时使用AddListDetailList 组件。这对你不起作用。如果您使用的是反应路由器,请使用 Route 组件,如 @Dlucidone 所说
    • 没问题,这对我来说是额外的知识。谢谢分享
    • 不客气,这里是关于解除国家的官方文档:reactjs.org/docs/lifting-state-up.html
    • 你能在上面的答案中回答我最后的评论吗
    猜你喜欢
    • 1970-01-01
    • 2019-06-16
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 2012-09-25
    • 2020-10-03
    • 1970-01-01
    相关资源
    最近更新 更多