代码之家  ›  专栏  ›  技术社区  ›  Cuzto

React将onClick值从一个类传递到另一个类

  •  0
  • Cuzto  · 技术社区  · 8 年前

    在锦标赛中。js I有一个锦标赛名称列表,每个名称都有从API获取的唯一ID。现在,每当我单击其中一个锦标赛名称时,我都会得到它的ID,但我需要将此ID传递给模板。js,我可以根据单击的锦标赛ID获取锦标赛数据。我正试着把道具从孩子传给父母,但我现在完全迷路了。

    锦标赛js公司:

    import React, { Component } from "react";
    import Template from './template';
    
    const API = 'http://localhost:8080/api/tournaments';
    
    class Tournaments extends Component {
    
      constructor() {
        super();
        this.state = {
          data: []
        }
      }
    
      componentDidMount() {
        fetch(API)
        .then((Response) => Response.json())
        .then((findresponse) => {
          console.log(findresponse)
          this.setState({
            data:findresponse,
          })
        })
      }
    
      reply_click(event) {
        var targetId = event.target.getAttribute('id');
        console.log(targetId);
      }
    
      render() {
        return(
          <div class="container">
            <div class="row">
              <div class="col-md-6 col-md-offset-3">
                <div class="jumbotron text-center">
                  {
                    this.state.data.map((dynamicData, key) =>
                    <div>
                      <a href={"/#/template"} id={dynamicData.id} onClick={this.reply_click}>{dynamicData.name}</a>
                      <a href={"/#/addTeams"}><button type="button" class="btn-lisa">Edit</button></a>
                      <Template name={dynamicData.id}></Template>
                    </div>
                    )
                  }
                </div>
              </div>
            </div>
          </div>
        )
      }
    }
    
    export default Tournaments;
    

    样板js公司:

    import React, { Component } from "react";
    import Parser from 'html-react-parser';
    import Tournaments from "./Tournaments";
    import './template.css';
    import './index.css';
    
    const tournyAPI = 'http://localhost:8080/api/tournaments';
    const teamAPI = 'http://localhost:8080/api/teams'
    
    class template extends Component {
    
      constructor() {
        super();
        this.state = {
          data: [],
        }
      }
    
      componentDidMount() {
        fetch(tournyAPI)
        .then((Response) => Response.json())
        .then((findresponse) => {
          this.setState({
            tournydata:findresponse.filter(res => res.id === 18),
          })
        })
    

    所以基本上我的目标是使用锦标赛中的targetID。js代替模板中ComponentDidMount中的“18”。js公司

    3 回复  |  直到 8 年前
        1
  •  1
  •   Denys Kotsur    8 年前

    应将此值保留在父级组件中 state 把它作为道具传给孩子。

    当您的 onClick 被解雇了你应该更新父母 状态 如此更新 props 将传递给孩子。

    代码如下:

    锦标赛js公司

    import React, { Component } from "react";
    import Template from './template';
    
    const API = 'http://localhost:8080/api/tournaments';
    
    class Tournaments extends Component {
    
      constructor() {
        super();
        this.state = {
          data: [],
          targetId: null,
        }
      }
    
      componentDidMount() {
        fetch(API)
        .then((Response) => Response.json())
        .then((findresponse) => {
          console.log(findresponse)
          this.setState({
            data:findresponse,
          })
        })
      }
    
      reply_click = id => {
        return () => {
            this.setState({ targetId: id })
        }
      }
    
      render() {
        return(
          <div class="container">
            <div class="row">
              <div class="col-md-6 col-md-offset-3">
                <div class="jumbotron text-center">
                  {
                    this.state.data.map((dynamicData, key) =>
                    <div>
                      <a href={"/#/template"} onClick={this.reply_click(dynamicData.id)}>{dynamicData.name}</a>
                      <a href={"/#/addTeams"}><button type="button" class="btn-lisa">Edit</button></a>
                      <Template name={dynamicData.id} targetId={this.state.targetId}></Template>
                    </div>
                    )
                  }
                </div>
              </div>
            </div>
          </div>
        )
      }
    }
    
    export default Tournaments;
    

    样板js公司

    import React, { Component } from "react";
    import Parser from 'html-react-parser';
    import Tournaments from "./Tournaments";
    import './template.css';
    import './index.css';
    
    const tournyAPI = 'http://localhost:8080/api/tournaments';
    const teamAPI = 'http://localhost:8080/api/teams'
    
    class template extends Component {
    
      constructor() {
        super();
        this.state = {
          data: [],
        }
      }
    
      componentDidMount() {
        fetch(tournyAPI)
        .then((Response) => Response.json())
        .then((findresponse) => {
          this.setState({
            tournydata: findresponse.filter(res => res.id === this.props.targetId),
          })
        })
    

    但是使用 componentDidUpdate 而不是 componentDidMount 如果您想随时更新 样板 每次更换后的组件 targetId

    像这样:

    样板js公司

    componentDidUpdate(prevProps) {
        if (prevProps.targetId !== this.props.targetId) {
           fetch(tournyAPI)
           .then((Response) => Response.json())
           .then((findresponse) => {
           this.setState({
              tournydata:findresponse.filter(res => res.id === this.props.targetId),
           })
          })
        }
    }
    

    如果需要在第一次渲染时立即执行,只需添加检查 targetId 不是 null 在您的 Tournament 组成部分

    类似这样:

    锦标赛js公司

    render() {
        ...
        {this.state.targetId ? <Template name={dynamicData.id} targetId={this.state.targetId}></Template> : null }
        ...
    }
    
        2
  •  0
  •   Roy Wang    8 年前

    添加 targetID 到父州并作为道具传递给子州:

    reply_click(event) {
      var targetId = event.target.getAttribute('id');
      this.setState({ targetID });
    }
    <Template targetID={this.state.targetID}
    

    在里面 Template 您可以使用访问它 this.props.targetID

    您需要使用 componentDidUpdate 尽管如此,请参见 React Child component don't update when parent component's state update

        3
  •  0
  •   Milos Mosovsky    8 年前

    在您的示例中,渲染时非常简单 <Template> 在循环中,您可以将其作为参数传递

    问题1

    React的目的不是像这样操纵dom var targetId = event.target.getAttribute('id') 您有这个id,为什么要从DOM中获取它?相反,将其作为参数接受

     <a href={"/#/template"} id={dynamicData.id} onClick={(e) => this.reply_click(e, dynamicData.id)}>{dynamicData.name}</a>
    

    reply_click(event, targetId) {
    
        console.log(targetId);
      }
    

    永远不要在React中查询DOM。由于未装载的元素等,您会遇到混乱和错误。React使用JSDom(内存中)而不是真正的DOM

    问题2

    只需将其作为参数传递

    并在内部调用setState reply_click

    reply_click(event, targetId) {
    
        console.log(targetId);
        this.setState({targetID: targetId})
      }
    
    推荐文章