【问题标题】:onClick affecting another element but same react componentonClick 影响另一个元素但相同的反应组件
【发布时间】:2019-11-11 15:35:19
【问题描述】:

如果标题没有解释太多,我很抱歉。我有一个反应组件,它有一个按钮和一些文本,我用了 3 次。我希望每个按钮在单击时显示其文本,但隐藏其他文本。

我编写的代码使我能够在单击每个按钮时显示文本,但它不会隐藏其他按钮的文本。我可以制作 3 个组件,每个按钮一个,但我想尝试这种方法,我不确定我是否可以让另一个也起作用

反应组件:

import React from 'react'
export default class Button extends React.Component {
    state={
        display: 'none'
    }
    render() {
        return (<div>
            <button
                onClick={()=>this.setState({display:'block'})}
                style={{ width: "50px", height: "50px", display:"inline-block" }}>
                {this.props.children}
            </button>
            <h1 style={{display: this.state.display}}>
                {this.props.title}
            </h1>
            <img style={{display: this.state.display}} src={this.props.src} alt=""></img>
            <p style={{display: this.state.display}}>
                {this.props.descri}
            </p>
        </div>)
    }
}

App.js:

import React from 'react';
import './App.css';
import Button from './sarra.js';
import Aa from './Aa.jpg';
import kacem from './b1.jpg';
import harold from './kacem.JPG';
/*
const person = [
  {name:"sarah",
    imgsrc:"" ,
  description: "ipsum lorem " 
  },
  {name:"sarah",
    imgsrc:"" ,
  description: "ipsum lorem " 
  },
  {name:"sarah",
    imgsrc:"" ,
  description: "ipsum lorem " 
  }

]
*/
const isShown =() =>{
 Button.style="backgroundColor: red"
}
function App() {
  return (<div>
<Button title="Aa" descri="this is ali's profile" src={Aa} >ali</Button>

<Button title="harold" descri="this is harold's profile" src={harold} onClick={isShown()}>harold</Button>

<Button title="kacem" descri="this is kacem's profile" src={kacem} >kacem</Button>



  </div>
  );
}

export default App;

我也想过做一个函数来隐藏其他按钮,所以我做了一个简单的函数来简单的启动,就是isShown让按钮变成红色,但是没有成功。我不知道出了什么问题,所以如果我知道问题出在哪里,我可以更改它,以便使用它们的 ID 将其他按钮的显示更改为隐藏。 也许我也可以使用状态?在定义了 onclick 道具的组件中,是否可以编写另一行,使其他按钮的显示隐藏,另一个按钮 this.setState({display:'block'} 还在那儿?是否有与this 相悖的东西影响其他元素?

如果可能,您还可以向我展示如何在同一行中制作三个按钮。谢谢!

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    工作codesandbox

    Button.js

    import React from "react";
    const clicked = {
      width: "50px",
      height: "50px",
      display: "inline-block"
    };
    
    export default class Button extends React.Component {
      state = {
        status: false
      };
    
      clickButton = () => {
        const status = this.props.status;
        this.setState({ status: !status });
        this.props.onChange(this.props.user.id);
      };
      render() {
        return (
          <div style={{ float: "left" }}>
            <button
              onClick={this.clickButton}
              style={this.props.status ? clicked : null}
            >
              {this.props.children}
            </button>
            {this.props.status && (
              <div>
                <h1>{this.props.user.name}</h1>
                <img
                  src={this.props.user.imgSrc}
                  style={{ width: "30px" }}
                  alt=""
                />
                <p>{this.props.user.description}</p>
              </div>
            )}
          </div>
        );
      }
    }
    

    App.js

    import React from "react";
    import Button from "./Button";
    
    const userList = [
      {
        id: 1,
        name: "user1",
        description: "user1 profile",
        imgSrc:
          "https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Brad_Pitt_Fury_2014.jpg/330px-Brad_Pitt_Fury_2014.jpg"
      },
      {
        id: 2,
        name: "user2",
        description: "user2 profile",
        imgSrc:
          "https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Brad_Pitt_Fury_2014.jpg/330px-Brad_Pitt_Fury_2014.jpg"
      },
      {
        id: 3,
        name: "user3",
        description: "user3 profile",
        imgSrc:
          "https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Brad_Pitt_Fury_2014.jpg/330px-Brad_Pitt_Fury_2014.jpg"
      }
    ];
    export default class App extends React.Component {
      state = {
        selectedUserId: null
      };
      handleClick = id => {
        this.setState({ selectedUserId: id });
      };
      render() {
        return userList.map(user => (
          <div key={user.id}>
            <Button
              status={user.id === this.state.selectedUserId ? true : false}
              user={user}
              onChange={this.handleClick}
            >
              {user.name}
            </Button>
          </div>
        ));
      }
    }
    
    

    我必须删除一些图像和 js 文件才能运行您的代码。 为了将它们对齐在一行中,有几种方法,我使用的一种方法是将float:left 应用于每个 Button 组件。 如果有帮助,请告诉我。

    【讨论】:

    • 感谢您的努力!然而,一个小细节是,例如,当我点击 harold 时,我只希望 harold 在那里,而其他人则隐藏起来。您的代码,正如我在阅读后测试的那样,使我能够单击一个按钮来显示和隐藏其内容,但这并不影响其余部分——我的问题是关于什么的!
    • @AliChbinou 对不起!我更新了codesandbox link 以及我的答案中的代码块。
    【解决方案2】:

    App.js 必须有一个持有活动按钮的状态,然后它可以决定要显示哪些文本,并且您必须给每个人一个唯一的 id 才能指定所选的。

    App.js

    ...
    state = {
      selected: null;
    }
    ...
    render() {
      const persons = [
        {
          id: '001',
          name: 'sarah',
          discr: 'some description...'
        },
        {
          ...
        },
        ...
      ]
    
      return(
        persons.map((p, index) => (<Button {...p} active={this.state.selected === p.id} onClick={() => this.setState({selected: p.id})} />
    

    Button.js

    <button onClick={this.props.onClick}>
      {this.props.name}
    </button>
    { this.props.selected && <h1>
      {this.props.discr}
    </h1>}
    

    【讨论】:

    • 你能解释一下地图部分吗?我确实知道函数和所有内容,但我无法理解 {...p} 和活动部分:)
    • 而不是我编写了 3 个具有不同标题和描述的按钮,我只是编写了一个对象数组,每个对象都包含一个按钮的值,然后将其映射到 Button 组件,这样你的代码就变得很多了更清洁且可重现。
    • 其中 p 是这样的对象 {name: 'ali', discr: 'Chbinou'},与 .这只是另一种语法,但要短得多。
    • 和活动部分,正如您每次单击按钮时所看到的那样,该按钮的 id 存储在活动状态,这样我们可以通过检查哪个按钮将活动按钮与其他按钮分开id 等于活动状态(保存活动按钮的 id)。我们可以这样做 ,如果它们相等,则 active 为 true,否则为 false。然后在 Button 组件中,我使用传递的 prop active 来确定是否显示 h1 标签({ this.props.active &&

      {this.props.discript

      } )
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 2021-02-02
    • 2011-09-25
    相关资源
    最近更新 更多