简体   繁体   中英

How can I keep visual studio code from trashing my jsx code?

I've been working on a simple crud app using reactjs.

Here's a snippet of code

enter code here render() { return ( Products Manager < AddProduct onAdd = { this.onAdd } /> { this.state.products.map(product => { return ( < ProductItem key = { product.name } {...product } onDelete = { this.onDelete } onEditSubmit = { this.onEditSubmit } /> ); }) } );

Looks fine, nothing wrong there. However if I save this, VS Code does the following: tags separated from their angle brackets, etc. My questions is simple-how do I keep VS Code from trashing my code? enter code here render() { return ( < div className = "App" > < h1 > Products Manager < /h1> < AddProduct onAdd = { this.onAdd } is.state.products.map(product => { return ( < ProductItem key = { product.name } {...product } onDelete = { this.onDelete } onEditSubmit = { this.onEditSubmit } /> ); }) } < /div> );

You probably have an extension installed that is auto formatting your text. Prettier is one of the most popular ones. VSCode to my knowledge does not autoformat your code out of the box.

It seems like two issues may be contributing towards your issue. Your code is invalid, which might be preventing your formatter from working correctly.

First we can clean up your code so that it is valid Javascript. Two issues exist:

  1. You're missing a closing brace for your render function.
  2. Adjacent JSX elements must be assigned keys or wrapped in a React Fragment .

Here's what the valid Javascript looks like after fixing these issue:

render() {
  return (
    <React.Fragment>
      Products Manager
      <AddProduct onAdd={this.onAdd} />
      {this.state.products.map(product => {
        return (
          <ProductItem
            key={product.name}
            {...product}
            onDelete={this.onDelete}
            onEditSubmit={this.onEditSubmit}
          />
        );
      })}
    </React.Fragment>
  );
}

VSCode has a built in Javascript Language Service which allows the editor to support Javascript features out-of-the-box. Learn more here .

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