簡體   English   中英

使用react jsx將jsx元素添加到主體

[英]add jsx element to body with react jsx

我有一個要添加到我身體末端的元素:

const nRecipe = 
<div id = "container">
<div className="recipe App" id="four" 
onClick={this.toggleRecipeList.bind(this)}>{this.state.recipeName}
</div>

<div style={{display:"none"}}>    
{this.state.value4.split(",").map((e)=>
  <p>{e}</p>)}

 <button onClick={this.deleteRecipe}>Delete</button>
<button name="4" onClick={this.openEditBox}>Edit</button>
</div></div>

創建此元素的按鈕如下:

<button onClick={this.newRecipe.bind(this)}>Enter</button>

該函數定義如下:

newRecipe(){
document.body.appendChild({nRecipe});}

我也嘗試過

newRecipe(){
document.body.insertAdjacentElement("beforeend", {nRecipe});}

我收到的錯誤消息是TypeError:

Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

&&

TypeError: Failed to execute 'insertAdjacentElement' on 'Element': 
parameter 2 is not of type 'Element'.

我找不到任何直接回答此問題的問題。 我不希望在顯示和隱藏元素之間切換,我想要一個可以使用文檔對象模型方法創建由jsx定義的元素的按鈕。

看起來您在單擊按鈕時試圖顯示元素:

  1. 使用狀態來管理元素可見性:
constructor(props) {
        super(props);
        this.state = {
         showNewRecipe: false
       };
    }
  1. 使用功能切換狀態
toggleNewRecipe(){
       this.setState(prevstate => ({
         ...prevState,
       showNewRecipe: !prevstate.showNewRecipe
     }));
    }
  1. 使用邏輯運算符在JSX中的任何位置呈現dom元素:
{
     this.state.showNewRecipe && (
      "your dom/JSX element"
     )
    }

暫無
暫無

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

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