如何使用react将jsx存储到变量中?

时间:2019-08-15 07:03:21

标签: reactjs

我是编程新手。我要实现以下内容,

当我单击列表项时,我想导航到另一个页面。

我要做什么?我在侧面板中有列表项。当我单击列表项时,它应该导航到另一页。

所以我有一个listpanel组件,它呈现了listitem组件。在单击列表项上,应基于item_data_type到达从get_type1_link方法获得的链接。但是,它返回一个对象。我不确定我在哪里犯错。

class ListPanel extends react.purecomponent {

    get_type1_link = () => {
        const item_data = this.props.item_data;
        const itemss = this.props.items;
        const {itemname, item_id} = item_data.properties;
        const filtered_item = items && items.find(item => item.id === 
        item_id); 
        const item_name = (filtered_item) ? filtered_item.itemname : 
        (itemname ? itemname : item_id);

        if (filtered_item) {
            return (<Link to={`/someurl/${item_data.properties.item_id}`}> 
            {item_name}</Link>);
        } else {
            return <span>{item_name}</span>;
        }
    };
    get_link = () => {
        const item_data = this.props.item_data;
        let link;
        switch (item_data.type) {
            case 'type1':
                link = this.get_type1_link();
                break;
            case 'type2':
                link = this.get_type2_link(); //some method similar to 
                //get_type1_link method
                break;
            default:
                return link=window.location.href;
        }
        return link;
    };
    render = () => {
        const list_item = this.props.;
        return (
            <ListItem
                key={list_item.id}
                text={this.get_text}
                link={this.get_link}/>
        );
    }

class ListItem extends react.purecomponent {
    render = () => {

        <li onClick={props.link}>
            <div className="text">
                {this.props.text}
            </div>
        </li>
    }
 }

我认为将get_type1_link方法返回的值存储到变量link中的方式存在问题。因为get_type1_link返回jsx(链接)。有人可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

我认为您的extends存在问题,

class ListPanel extends react.purecomponent {

应该是

class ListPanel extends React.PureComponent {

另一个问题是您的render函数,您什么也没有返回。您的render函数应return类似于

class ListItem extends React.PureComponent {
    render = () => {
       return(
        <li onClick={this.props.link}> //props.link should be this.props.link
            <div className="text">
                {this.props.text}
            </div>
        </li>
       )
    }
 }