简体   繁体   中英

H1 tag value not showing when page loads up in React

Problem: when the page first loads up, the PageHeader H1 tag shows a blank value instead of "New Page". Why does this happen and how can I make it show "New Page"?

In Page.js

const [pageTitle, setPageTitle] = useState('New Page');
const pageTitleChangeHandler = (e) => {
    setPageTitle(e.target.innerText);
}

return (
     <PageHeader title = {pageTitle} onChange = {pageTitleChangeHandler}></PageHeader>
);

In PageHeader.js

return (
        <div className = "page-header">
            <h1 
                className = "page-header-text" 
                contentEditable = "true" 
                onInput = {props.onChange} 
                value = {props.title}>
            </h1>
        </div>
);

I think you should remove value attribute from h1 tag and set dangerouslySetInnerHTML instead like

import React from "react";
export default function PageHeader(props) {
  return (
    <div className="page-header">
      <h1
        className="page-header-text"
        contentEditable="true"
        onInput={props.onChange}
        dangerouslySetInnerHTML={{ __html: props.title }}
      >
      </h1>
    </div>
  );
}

If you want New Page to show up on page load, you need to change the argument to setPageTitle from e.target.innerText to e.target.value , and add {props.title} in the h1 tag.

Then you can change onInput to onKeyDown .

const [pageTitle, setPageTitle] = useState('New Page');
const pageTitleChangeHandler = (e) => {
    // This will set the value prop
    setPageTitle(e.target.value);
}

  return (
    <PageHeader
      title={pageTitle}
      onChange={pageTitleChangeHandler}
    ></PageHeader>
  );
}

const PageHeader = (props) => {
  return (
    <div className="page-header">
      <h1
        className="page-header-text"
        contentEditable="true"
        onKeyDown={props.onChange}
        value={props.title}
      >
        {props.title}
      </h1>
    </div>
  );

Note that this will delete "New Page" and replace it with the typed text.

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