React JSX and Django reverse URL

北城余情 提交于 2020-02-02 11:16:11

问题


I'm trying to build some menu using React and need some Django reverse urls in this menu. Is it possible to get django url tag inside JSX? How can this be used?

render: function() {
    return <div>
        <ul className={"myClassName"}>

            <li><a href="{% url 'my_revese_url' %}">Menu item</a></li>

        </ul>
    </div>;
} 

回答1:


You could create a script tag in your page to inject the values from Django into an array.

<script>
  var menuItems = [
    {title: 'Menu Item', url: '{% url "my_reverse_url" %}'},
    {title: 'Another Item', url: '{% url "another_reverse_url" %}'},
  ];
</script>

You could then pass the array into the menu through a property.

<MyMenu items={menuItems}></MyMenu>

Then loop over it to create the list items in your render method.

render: function(){ 
  var createItem = function(itemText) {
    return <li>{itemText}</li>;
  };
  return <ul>{this.props.items.map(createItem)}</ul>;
}

This will keep your component decoupled and reusable because the logic for creating the data and the logic for displaying the list items is kept separate.



来源:https://stackoverflow.com/questions/40232541/react-jsx-and-django-reverse-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!