简体   繁体   中英

How to store values from input field that is set by dangerouslySetInnerHTML React?

How to read all the entered input values comma separated. Here i am trying to set html using ````dangerouslySetInnerHTML```. The html contain three input field, how can i read valued entered in all the three input field.

Suppose I entered 24 in first input field then 12 in second input field and 2 in third input field. So now i want to save all the values in state variable comma separated ie

But handleChange function is not working

import React, { useState, useEffect } from "react";
import "./styles.css";

const data = {
  htmltag: `<div><p><input type = 'text' /></p><p><input type = 'text' /></p><p><input type = 'text' /></p></div>`
};

export default function App() {
  const [state, setState] = useState("");


  const handleChange = () => {
    console.log(" Inside of handleChangeOption Scenario");
    const inputs = Array.from(document.querySelectorAll("#my-inputs input"));
    const formDataArray = inputs.map(input => input.value);
    console.log(formDataArray);
    const x = formDataArray.toString();
    console.log(x);
    setState(x);
  };

  useEffect(() => {
    console.log(state);
  }, [state]);


  return (
    <>
      <div
        id="my-inputs"
        onChange={handleChange}
        dangerouslySetInnerHTML={{ __html: data.htmltag }}
      />
      <p>values comma separated: {state} </p>
    </>
  );
}

You would need to do a mix of query selectors on and local state management.

Click the "Run code snippet" below.

 // main.js const { useEffect, useState } = React; const htmlData = { htmltag: `<div><p><input type="text" placeholder="Enter text here" /></p></div>` }; const App = () => { const [data, setData] = useState(''); const onKeyUp = event => { setData(event.target.value); } useEffect(() => { const divId = document.querySelector('#my-inputs'); const input = divId.querySelectorAll('input'); if (input && input.length > 0) { input[0].addEventListener('keyup', onKeyUp); } }, []); return <div><h3>HTML Generated:</h3><div id="my-inputs" dangerouslySetInnerHTML={{ __html: htmlData.htmltag }} /><hr /><h3>Result:</h3><code>{JSON.stringify(data)}</code></div> } ReactDOM.render(<App />, document.getElementById('root'));
 code { padding: 10px; background: #efefef; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM