簡體   English   中英

如何在不渲染組件的情況下傳遞道具?

[英]How to pass props without rendering the component?

我有兩個組件,一個名為ReturningCustomer ,另一個名為Update 我在ReturningCustomer中保存了狀態的電話號碼,我想將該電話號碼傳遞給更新組件,而不必渲染更新或使用Redux:

render() {
       return (
        <div className="row returning-customer">
            <h3>Returning Customer</h3>
            <div className="col">
                <p className="error">{this.state.error}</p>
                <form className="row" onSubmit={this.onSubmit}>
                    <label>Phone Number</label>
                    <input 
                        type="text"
                        className="validate"
                        onChange={this.onPhoneNumberChange}
                    />
                    <button className="btn">Go</button>
                </form>
            </div>
            <Update 
                phoneNumber={this.state.phoneNumber} 
            />
        </div>
    );

}

根據當前的描述,你所要求的並不完全清楚,但聽起來你想要在傳遞道具時有條件地渲染組件,或者你想知道如何使用這些道具? 我在這里包括兩個。

有條件地渲染組件並傳遞道具:

// SomeComponent.js

import React from 'react'
import Update from '../..'

class SomeComponent extends React.Component {
  state = { phoneNumber: '' };

  renderUpdate() {
    const someCondition = true;

    if (someCondition) {
      return <Update phoneNumber={this.state.phoneNumber} />
    }

    return null
  }

  render() {
    return (
      <div>
        {this.renderUpdate()}
      </div>
    )
  }
}

export default SomeComponent

使用道具:

// Update.js

import React from 'react'

// destructuring the props object here
const Update = ({ phoneNumber }) => (
   <div>
     <p>{phoneNumber}</p>
   </div>
)

export default Update

在Update的渲染函數中,您可以使用以下任一項,並且組件不會呈現

render() { 
   return false; 
}

render() { 
   return null; 
}

render() { 
   return []; 
}

render() { 
   return <></>; 
}

暫無
暫無

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

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