簡體   English   中英

如何通過單擊組件外部的按鈕來刷新 React 組件?

[英]How do I refresh a react component by clicking on a button outside the component?

我是 web 開發的新手,決定學習 ReactJs。我正在嘗試創建一個隨機報價生成器作為 freecodecamp 前端庫項目的一部分。 問題:我有一個反應組件,它從網站獲取報價,然后在屏幕上顯示隨機報價。 我在組件外部還有一個按鈕,其唯一目的是獲取新代碼並將其顯示在屏幕上。 單擊按鈕時如何刷新反應組件? 感謝任何幫助::D 這是我的組件:

 class MyComponent extends React.Component { constructor(props) { super(props); this.state = { quote: '' }; } componentDidMount() { fetch("https://type.fit/api/quotes").then(res => res.json()).then( (result) => { this.setState({ quote: result[Math.floor(Math.random() * result.length)] }); }, ) } render() { return ( <p id = 'reactQuote'>{this.state.quote.text}< /p> ); } } ReactDOM.render( MyComponent />, document.getElementById('text'))
 <div id="text"></div> <button id='new-quote'>New Quote</button>

創建一個組件來封裝按鈕和您的組件,在上部組件中引用 state 並將其作為道具傳遞給您的組件,現在當您按下按鈕時,它將更改上部組件中的 state 並且它將傳遞給您的組件,迫使它刷新並顯示新報價。

每當您單擊按鈕時,您都可以在按鈕上撥打 function。 function 可以作為道具傳遞給您的按鈕組件。

function fetchData(){
     fetch("https://type.fit/api/quotes")
        .then(res => res.json())
        .then(
          (result) => {
            this.setState({
              quote: result[Math.floor(Math.random() * result.length)]
          });
        },
      )
}

<button id='new-quote' onClick={fetchData}>New Quote</button>

該組件將在其 state 更改時自動刷新,但按鈕和文本應該是組件本身的一部分(或組件的子組件)。 一個示例(使用單個組件)是:

 // your component class RandomQuoteMachine extends React.Component { constructor() { super(); this.state = { quotes: [], // here you store an array of quote objects currentQuote: null // here you store the quote object that is currently displayed }; this.getRandomQuote = this.getRandomQuote.bind(this) } // when the component mounts, fetch the quotes from the API componentDidMount() { fetch("https://type.fit/api/quotes") // fetch the entire list of quotes from the API.then(response => response.json()) // turn the response into a Javascript object.then(result => { // update the state this.setState({ quotes: result, currentQuote: result[Math.floor(Math.random() * result.length)] || null }); }); } getRandomQuote() { // randomly select a quote from the state const newQuote = this.state.quotes[Math.floor(Math.random() * this.state.quotes.length)] || null; // update the state with the new current quote this.setState({ currentQuote: newQuote }); } render() { return ( <div> <blockquote>{ this.state.currentQuote && this.state.currentQuote.text || '' }</blockquote> <p className = "author">{ this.state.currentQuote && this.state.currentQuote.author || 'unknown' }</p> <button onClick = { () => this.getRandomQuote() }>get a new quote from the list</button> </div> ); } } // mounting the component in the page ReactDOM.render( < RandomQuoteMachine / >, document.getElementById('app'))
 /* A bit of styling, just for presentation sake */ * { font-family: sans-serif; } blockquote { font-size: 2rem; font-style: italic; margin: 0; padding: 0.5rem 0.5rem 0.5rem 3rem; border-left: 3px solid #ccc; }.author { font-size: 1.2rem; padding-right: 0.5rem; text-align: right; }.author::before { content: "("; }.author::after { content: ")"; }
 <:-- Importing React and ReactDOM --> <script crossorigin src="https.//unpkg.com/react@17/umd/react.production.min:js"></script> <script crossorigin src="https.//unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script> <!-- This is where your component will be mounted --> <div id="app"> </div>

或者,如果您更喜歡功能組件和掛鈎:

 const RandomQuoteMachine = () => { const [quotes, setQuotes] = React.useState([]); const [currentQuote, setCurrentQuote] = React.useState(null); React.useEffect(() => { fetch("https://type.fit/api/quotes").then(response => response.json()).then(result => { setQuotes(result); setCurrentQuote(result[Math.floor(Math.random() * result.length)] || null); }) }, [setQuotes, setCurrentQuote]); const getRandomQuote = React.useCallback(() => { const newQuote = quotes[Math.floor(Math.random() * quotes.length)] || null; setCurrentQuote(newQuote) }, [quotes, setCurrentQuote]); return ( <div> <blockquote> { currentQuote && currentQuote.text || '' } </blockquote> <p className = "author"> { currentQuote && currentQuote.author || 'unknown' }</p> <button onClick = { () => getRandomQuote() }> get a new quote from the list </button> </div> ); } ReactDOM.render(<RandomQuoteMachine />, document.getElementById('app'));
 * { font-family: sans-serif; } blockquote { font-size: 2rem; font-style: italic; }.author { font-size: 1rem; text-align: right; }.author::before { content: "("; }.author::after { content: ")"; }
 <script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script> <div id="app"> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM