簡體   English   中英

如何在危險的SetInnerHTML中設置默認值反應?

[英]How to set default value in dangerouslySetInnerHTML in react?

1.創建react組件——customhtmlelement

<customelement>
    <div dangerouslySetInnerHTML={{ __html: this.props.customHtml }} />
</customelement>

2.react組件的使用

<customhtmlelement
 customHtml="<input value={value} disable='true' placeholder='Enter text' type='text' id='test'</input>"/>><<customhtmlelement/>

在文本框中設置默認值。

let value= "test";

它不工作。 如何在innerHtml設置默認值?

試試這個,它可能會有所幫助

import React from "react";
import ReactDOM from "react-dom";
const value = "test";

// inner HTML Example...
function createMarkup() {
  return {
    __html: "<input value="+value+" disable='true' placeholder='Enter text' type='text' id='test'</input>"
  };
}

//React component...
function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

const rootElement = document.getElementById("root");
ReactDOM.render(<MyComponent />, rootElement);

為什么要使用dangerouslySetInnerHTML SetInnerHTML 呈現輸入?

無論如何,您的代碼並不是真正有效的。

嘗試這個:

function CustomHTMLElement(props) {
  return <div dangerouslySetInnerHTML={{__html: props.customHtml}} />
}

function App() {
  const value = 'Test Value'

  return (
    <div>
      <CustomHTMLElement
        customHtml={`<input id='test' type='text' placeholder='Enter text' value='${value}' disabled=${true} />`}
      />
    </div>
  )
}

你需要像這樣使用,在模板文字的幫助下

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

let value = "text";

function CustomHtmlElement(props) {
  return <div dangerouslySetInnerHTML={{ __html: props.customHtml }} />;
}

function App() {
  return (
    <div className="App">
      <CustomHtmlElement
        customHtml={`<input value=${value} disable='true' placeholder='Enter text' type='text' id='test'</input>`}
      />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

工作示例代碼和框

暫無
暫無

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

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