【问题标题】:onClick event binding (not a button)onClick 事件绑定(不是按钮)
【发布时间】:2021-03-28 01:58:52
【问题描述】:

我有一个小型 React 应用程序,它调用 JSON 文件并返回卡片的文本。

我通过在按钮上调用 onClick 成功完成了这项工作,但我真正想做的是将 onClick 作为事件添加到我创建的 Cards 模块中。我已经研究过这个级别的绑定,但没有成功;

<Cards name={card} onClick={() => setCard(Math.floor(Math.random() * 57) + 1)}/>

我是否需要在我的 cards.js 中编写一个自定义处理程序来处理 onClick?或者我可以在这个文件(App.js)中附加它吗?

完整代码如下。

import React, { useState } from 'react';
import './App.css';
import Cards from '../cards';

function App() {
  const [card, setCard] = useState('1');

  return (
    <div className="wrapper">
      <h1>Card text:</h1>
      <button onClick={() => setCard(Math.floor(Math.random() * 57) + 1)}>Nile</button>
      <Cards name={card} />
    </div>
  );
}

export default App;

我的card.js组件代码是;

export default function Cards({ name }) {
  const [cardInformation, setCards] = useState({});
  
  useEffect(() => {
    getCards(name)
    .then(data =>
      setCards(data)
    );
  }, [name])
  
  const FlippyOnHover = ({ flipDirection = 'vertical' }) => (
    <Flippy flipOnHover={true} flipDirection={flipDirection}>
    </Flippy>
  );

  return(
    <div>
      <Flippy flipOnHover={false} flipOnClick={true} flipDirection="vertical" style={{ width: '200px', height: '200px' }} >
    <FrontSide style={{backgroundColor: '#41669d',}}>
    </FrontSide>
    <BackSide style={{ backgroundColor: '#175852'}}>
      {cardInformation.continent}
    </BackSide>
  </Flippy>
      <h2>Card text</h2>
      <ul>
        <li>{cardInformation.continent}</li>
      </ul>
    </div>
  )
}

Cards.propTypes = {
 name: PropTypes.string.isRequired
}

【问题讨论】:

  • 根据你的说法 setCard 现在不适合你吗?
  • 能否请您也添加卡组件代码sn-p?
  • @AbuSufian 我已经添加了卡片组件代码

标签: javascript reactjs


【解决方案1】:

我们可以创建一个事件。所以我们称之为onSetCard

App.js文件:

class App extends Component {
     handleSetCard= () => {
        // set state of card here
     };

     <Cards name={card}
      card=card
      onSetCard={this.handleSetCard} 
     />
}

Cards.js文件:

class Cards extends Component {
    render() {
        console.log("Cards props", this.props);  
        return (
            <button
                onClick={() => this.props.onSetCard(this.props.card)}
                className="btn btn-secondary btn-sm m-2"
             >
            FooButton
            </button>

        )
    }
}

【讨论】:

    猜你喜欢
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-24
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    相关资源
    最近更新 更多