问题描述:

i have a toolbar component and 3 options to add text, image and video element to main page component, i write a click handle in main page component and pass this event handler to toolbar component.

my simple idea is that a switch with a parameter that define the type of element but i don't know how to render them.

how can i do this?

class ToolbarContainer extends React.Component {

constructor(props) {

super(props);

}

render() {

return (

<div id="toolbarSection">

<div class="option" onClick={this.props.handleActionsClick("image")}>new Image</div>

<div class="option" onClick={this.props.handleActionsClick("text")}>new Text</div>

<div class="option" onClick={this.props.handleActionsClick("shape")}>new Shape</div>

</div>

);

}

}

class Page extends React.Component {

constructor(props) {

super(props);

}

handleActionsClick(type){

switch(type){

case "image":

//How can i render the <img/>?

case "text":

case "video":

}

}

render() {

return ();

}

}

网友答案:

Use createElement instead, which is what JSX uses under the hood.

You can then pass in a custom component to the click handler or a string for the native elements like 'img'.

I am using stateless component here but you can also just use classes if you need.

const ToolBarContainer = ({ handleActionsClick }) => (
    <div id="toolbarSection">
        <div class="option" onClick={handleActionsClick('img')}>new Image</div>
        <div class="option" onClick={handleActionsClick(Text)}>new Text</div>
        <div class="option" onClick={handleActionsClick(Shape)}>new Shape</div>
    </div>
);

class Page extends React.Component {
    constructor(props) {
        super(props);

        this.state = {};
        this.handleActionsClick = this.handleActionsClick.bind(this);
    }

    handleActionsClick(type){
        this.setState({ type });
    }

    render() {
        return React.createElement(this.state.type);
    }
}
相关阅读:
Top