![](/img/trans.png)
[英]How can I access a functional components state outside the component? - React
[英]How do I access a component's state data outside of the component in react?
我正在為 flash 卡 Q/A 應用程序使用 npm 庫 react-flippy。 我有一個 Q/A 對象數組作為減速器,一個隨機數作為組件 state。 當用戶單擊“下一步”按鈕時,會生成一個隨機數,以確定下一個 Q/A object 填充卡的正面和背面。
我遇到的問題是,如果單擊“下一步”按鈕時可以看到卡片的背面(答案),則卡片不會返回到正面(問題)以獲取下一個 Q/A 信息,它會留在背面顯示回答問題。
我查看了 react-flippy 模塊,試圖找到確定卡是否翻轉的變量/狀態(我假設它是一個名為 isFlipped 的 boolean)。 我需要在 Next 按鈕調用的 randomQuestion function 中將此變量重置為 false。 如何在 Flippy-react 模塊中找到執行此操作的變量/狀態,以及如何在 Flippy 元素之外訪問它?
用於 react-flippy 的 Github: https://github.com/sbayd/react-flippy
我的代碼:
import React from 'react';
import { connect } from 'react-redux';
import '../styles/style.css';
import Flippy, { FrontSide, BackSide } from 'react-flippy';
class MenuCards extends React.Component{
state = {
randomNumber: 0
}
randomQuestion = (arry=[]) => {
var num = Math.floor(Math.random() * arry.length);
this.setState({randomNumber: num});
//-- Need to reset isFlipped back to false here...
}
render() {
return(
<div className='ui container'>
<div style={{ margin: '2em' }} className='ui one column stackable center aligned page grid'>
<div style={{ margin: '2em' }} className='ui one column stackable center aligned page grid'>
<h1 className='ui header'>Food Menu Flash Cards</h1>
<div className='column twelve wide'>
<Flippy flipOnHover={false} flipOnClick={true} flipDirection='horizontal' ref={(r) => this.flippy = r}>
<FrontSide style={{ backgroundColor: 'maroon' }} id='question'>
<h2 id='text' className='ui header'>Question</h2>
<p id='text'>{ this.props.questionAnswer[this.state.randomNumber].question }</p>
</FrontSide>
<BackSide style={{ backgroundColor: 'maroon' }} id='answer'>
<h2 id='text' className='ui header'>Answer</h2>
<p id='text'>{ this.props.questionAnswer[this.state.randomNumber].answer }</p>
</BackSide>
</Flippy>
<button id='next-button' className='fluid ui button' onClick={() => this.randomQuestion(this.props.questionAnswer)}>Next</button>
</div>
</div>
</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
questionAnswer: state.questionAnswer
};
}
export default connect(mapStateToProps)(MenuCards);
這isFlipped
是您的Flippy
接受的道具,這意味着您可以從組件外部將卡片設置為翻轉或不翻轉(但是,根據官方文檔,您的flipOnHover
和 'flipOnClick' 不起作用)。 它沒有內部 state。
閱讀更多關於 React state 和 props 的信息——這些是基礎知識。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.