简体   繁体   中英

React component not rendering inline CSS

I am trying to write a react application where the App component renders an array of components to the screen. But the inline CSS are not showing up.

//App component
import data from "./data.js"
import Item from "./Item"

export default function App(){
   const cardElements = data.map(item => <Item/>)
   return (<div className='app'>
               {cardElements}
           </div>);
}
//Item component
export default function Item(){
   const customStyle = {border: "2px solid black"};
   return (<div style={customStyle} >Item component</div>);
}

The inline CSS in the Item component does not reflect on the webpage.

As you can see in the snippet below the inline style does indeed work. What is likely happening here is your style is bering overridden but we'd need more information to know for sure.

Sidenote: don't forget to add key prop when using .map in React.

 const data = [1, 2, 3, 4]; function App() { const cardElements = data.map(item => <Item key={item} />) return ( <div className='app'> {cardElements} </div> ); } function Item() { const customStyle = { border: "2px solid black" }; return <div style={customStyle}>Item component</div>; } ReactDOM.createRoot( document.getElementById("root") ).render( <App /> );
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>

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