React中实现列表项每行3个布局的问题排查与解决
Hey there! Let's break down why your 3-per-row event card layout isn't working in React (even though it works in plain HTML) and get it fixed step by step.
The Root Cause
Looking at your code, the main issues are structural and styling-related:
- Each
Eventcomponent wraps its card in a.wrapdiv withdisplay: flex—this means every single card is trapped in its own flex container, so they can't line up in rows together. - Your
EventsListuses a.rowdiv to hold all events, but this div lacks the necessary flex styling to act as a proper container for multiple cards. - The original
.wrapCSS was missingflex-wrap: wrap, which is essential for making items wrap into new rows when there's not enough horizontal space.
Step-by-Step Fixes
1. Clean Up the Event Component
Remove the outer .wrap div from the Event component—this container should belong to the entire list, not individual cards:
const Event = (props) => ( <div className="tile"> <img src={props.event.eventImage} /> <div className="text"> <h1>{props.event.title}</h1> <h2 className="animate-text">More lorem ipsum bacon ipsum.</h2> <p className="animate-text">{props.event.description}</p> <div className="dots"> <span /> <span /> <span /> </div> </div> </div> );
2. Update the EventsList Component
Change the outer container in EventsList to use the .wrap class (so it picks up the flex styling we need) and remove unnecessary nested divs:
export default class EventsList extends Component { constructor(props) { super(props); this.state = { events: [] }; } componentDidMount() { axios .get("http://localhost:9000/events/") .then((response) => { this.setState({ events: response.data }); }) .catch(function (error) { console.log(error); }); } eventList() { return this.state.events.map(function (currentEvent, i) { return <Event event={currentEvent} key={i} />; }); } render() { return ( <div className="wrap"> {this.eventList()} </div> ); } }
3. Fix the CSS for Flex Wrapping
Update your .wrap CSS to add flex-wrap: wrap (this enables row wrapping) and adjust alignment to space cards evenly:
.wrap { margin: 50px auto 0 auto; width: 100%; display: flex; flex-wrap: wrap; /* Critical for making cards wrap into new rows */ justify-content: space-around; /* Space cards evenly across each row */ align-items: flex-start; /* Align cards to the top of their row */ max-width: 1200px; }
Why This Works
Now your component structure matches the working plain HTML version:
- A single
.wrapflex container holds all your.tilecards. flex-wrap: wrapensures that when there's not enough space for 3 cards in a row, they'll automatically wrap to the next line.- Each card is a direct child of the flex container, so they can align properly in rows of 3.
Your existing hover effects and responsive media query (for screens under 1000px) will still work exactly as expected—this fix only addresses the row layout issue.
内容的提问来源于stack exchange,提问作者Chukwuma Kingsley

