[英]ReactJS two different components
我對ReactJS組件有疑問。 因為我是ReactJS的新手,請多多包涵。 我一直在弄清楚如何使用ReactJS做到這一點。 這是場景。
場景:
<div>
<button id="download-button">Download as CSV</button> <!-- This is a ReactJS Component -->
<h3>Filters</h3>
<form>
<!--
SOME FILTER FIELDS
-->
<input type="submit" value="Filter" />
</form>
</div>
<div>
<h2>Filtered Search Result</h3>
<div id="result" filters="<?php echo $filters ?>"></div> <!-- This is a ReactJS Component -->
</div>
問題:
在結果組件內部,如果結果為空,我想隱藏下載按鈕。 我知道,如果下載按鈕位於結果組件內部,則這很簡單。 但是在這種情況下,我只是不想編寫所有與結果組件無關的html元素,只是為了能夠訪問這些html元素頂部的結果按鈕。
在反應中,您的組件可以在render()
方法中返回null
所以這是有效的
// @flow
import React from "react";
Props = {
renderNull: boolean
}
const MyNullDecoratorComponent = (props: Props) => props.renderNull && null || "some text";
您可以將兩個Child組件都放入一個Parent組件中(具有checkResultLength方法和this.state.downloadVisible = true)。
將這兩個作為道具傳遞給結果Component。
在“ componentDidMount”中檢入結果組件,並調用從父組件傳遞的函數checkResultLength,該函數將設置state.downloadVisible = false(如果您的results.length === 0)。
this.state.downloadVisible將作為prop傳遞到您的Filter Form組件中,您可以相應地隱藏和顯示它
首先,您應該知道如何在兩個組件之間進行通信。 如果這兩個組件是父<->子代,則它們可以通過Props或函數回調進行通信。
您的組件不是父<->子關系,所以最好的方法是使用流量數據流。您可以將過濾器結果視為全局組件狀態。
我認為您應該學習Flux數據流,例如Redux,Alt.js等,它可以解決您的問題。
我用Alt.js,這里是我的演示在這里 ,我希望它會幫助你。
既然你是路過的result
道具的Result
,你可以很容易地只保護操作者添加到您的DownloadBtn
組件
class Result extends Component { render () { const { result } = this.props // is the same with const result = this.props.result return ( <div> {result.length >= 0 && <DownloadBtn /> } { // render results here } </div> ) } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.