【问题标题】:Passing variable to react component将变量传递给反应组件
【发布时间】:2022-01-31 23:44:03
【问题描述】:

我有:

        function Button(){
        /*.. useQuery ...*/
         const onClick = props => (
         console.log(props.target.value)
           )
        return(
          /*  ... */
            <button value={id} onClick={onClick} >details</button>
        )
        }
我想将 props.target.value 传递给 react.component 类。它将用于显示弹出窗口。 我想要类似的东西:
class Details extends React.Component{
/* if thereIsID == 0 then "" or if thereIsID == not 0 then show popup with data according to props.target.value */
}
我使用了许多不同的变体。也许我尝试的方法不对? 你能推荐一些东西吗?

【问题讨论】:

    标签: reactjs graphql apollo-client


    【解决方案1】:

    import React, { useState } from 'react';
    import './style.css';
    
    function Button({ onClickHandler }) {
      /*.. useQuery ...*/
      const onClick = (props) => {
        onClickHandler(props.target.value);
      };
      return (
        /*  ... */
        <button value={1} onClick={onClick}>
          details
        </button>
      );
    }
    
    class Details extends React.Component {
      /* if thereIsID == 0 then "" or if thereIsID == not 0 then show popup with data according to props.target.value */
    
      render() {
        return (
          <div>
            Details of Details : {this.props.detail === 0 ? '00000' : 'not 0000000'}
          </div>
        );
      }
    }
    
    export default function App() {
      const [show, setShow] = useState(false);
      const [detail, setDetail] = useState('');
    
      const onClickHandler = (val) => {
        setDetail(val);
        setShow((prev) => !prev);
      };
    
      return (
        <div>
          <Button onClickHandler={onClickHandler} />
          {show && <Details detail={detail} />}
        </div>
      );
    }

    测试链接:https://react-sjsxn2.stackblitz.io

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-22
      • 2016-05-26
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      • 2019-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多