简体   繁体   中英

React: Function inside my form's onSubmit handler not working properly

Forgive me, as I am only 2 days into learning React.

I have a SearchForm component, which is a simple form where a number can be submitted. I would like the onSubmit handler inside this form to display another component, called SearchResult, which for now only displays the number that we just looked up. For some reason, my webpage isn't displaying SearchResult, while SearchForm renders properly. Thank you so much!

function SearchForm( props ) {
  const [ trackNo, setTrackNo ] = useState('');

  function handleSubmit( event ) {
    event.preventDefault();
    // props.onSubmit( trackNo );
    <SearchResult trackingNum={trackNo}/>
    setTrackNo('');
  }
  return (
    <div className="SearchBar">
      <h3>Track a Package</h3>
      <form onSubmit={handleSubmit}>
        <input
        type="text"
        value={trackNo}
        onChange={ event => setTrackNo(event.target.value)}
        placeholder="Enter a Tracking Number"
        required
        />
        <button type="submit">Search</button>
      </form>
    </div>
  )
}

function SearchResult( props ){
  return (
    <div className="SearchResult">
      <b>Tracking Number: { props.trackingNum }</b>
    </div>
  )
}

You've declared a React element inside handleSubmit but aren't using it anywhere, so it does nothing. For similar reasons:

function handleSubmit( event ) {
    event.preventDefault();
    4;
}

does not result in the line with the 4 doing anything at all. It's an unused expression. ( Consider a linter. )

Add another state, one that determines whether the <form> is being shown, or whether the <SearchResult> is being shown, and change that state inside the submit handler.

If all the functionality was inside this component, it'd look like:

const [resultsTrackNo, setResultsTrackNo] = useState(-1);
function handleSubmit( event ) {
    event.preventDefault();
    setResultsTrackNo(Number(trackNo));
    setTrackNo('');
}
return resultsTrackNo === -1
  ? (
    <div className="SearchBar">
      ...
    </div>
  )
  : <SearchResult trackingNum={resultsTrackNo}/>;

If a track number is a number , you might consider changing <input type="text" to <input type="number" and using .valueAsNumber instead of .value .

You could also put the state into the parent, and have the parent conditionally render this SearchForm depending on whether resultsTrackNo is -1 or not (and, if not, render the SearchResult )

If it suits your purposes, you could also have the additional state be just a boolean flag, and use just the trackNo state. (If you were to go this route, you wouldn't want to reset the state on submit; the setTrackNo(''); line would be removed.)

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