可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have the following jsx code, I am trying to put some code out of the mapping function, but getting errors with the jsx syntax, I want this block displayed only if there is some data..
{this.props.someData ? <div className="container"> <h3>Heading</h3> <div className="block1"> <button>one</button> <buttontwo</button> </div> this.props.someData.map((response, index) => { return ( <div className="Block2"> <div key={index}> <span>{response.number}</span> </div> </div> </div> ); }) : ''}
回答1:
Write it like this:
{this.props.someData ? <div className="container"> <h3>Heading</h3> <div className="block1"> <button>one</button> <buttontwo</button> </div> {this.props.someData.map((response, index) => { return ( <div className="Block2"> <div key={index}> <span>{response.number}</span> </div> </div> )}) } </div> : <div/>}
Mistake you are doing:
To render any js code inside html elements, {} is required, since you are rendering JSX if the condition is true and inside that using map so put map function inside {}, it will work.
回答2:
You should be able to add a child { wrapping your map. You have a few other errors as well. You were cosing your tags and braces too early. Additionally, an "empty" JSX element should return null, not empty string. You also have broken syntax with no closing > here: <buttontwo</button>
Using a code editor that provides syntax highlighting, and using consistent spacing, and always using eslint to check for errors, will help prevent the need to come to StackOverflow and blocking your programming on syntax questions.
{this.props.someData ? <div className="container"> <h3>Heading</h3> <div className="block1"> <button>one</button> <button>two</button> </div> { this.props.someData.map((response, index) => { return ( <div className="Block2"> <div key={index}> <span>{response.number}</span> </div> </div> ); }) } </div> : null}
回答3:
If I get your meaning correctly, I think this would do:
{this.props.someData && (<div className="container"> <h3>Heading</h3> <div className="block1"> <button>one</button> <buttontwo</button> </div> {this.props.someData.map((response, index) => { return ( <div className="Block2"> <div key={index}> <span>{response.number}</span> </div> </div> ); })} </div>) }
I'd recommend you to have a look at the conditional rendering section of the documentation.