簡體   English   中英

如何不使用jsx格式呈現React組件?

[英]How I can render react components without jsx format?

我嘗試制作“智能”彈出組件,該組件可以在其內部打開某些組件,但是我的實現不好,因為它不起作用。

我使用redux方法創建彈出窗口,並且打開彈出窗口的操作能夠在打開彈出窗口之前獲取要渲染的任何組件的名稱;

但是我有一個問題,在獲取參數后,在我們的例子中是nameOfComponent ,我需要選擇並渲染名稱為nameOfComponent的組件。

現在我的問題是,它如何渲染數組中的組件?

// He's my components
import Login from '../Login/login.js';
import Logout from '../Logout/logout.js';


const popupContent = {
    Login : Login,
    logout: Logout
};

// My component 
class Popup extends Component {

    componentDidUpdate () {
        // for example
        const nameOfComponent = "Login";

        this.body = this.setBodyPopup(nameOfComponent);

        return true;
    }

    setBodyPopup(property){
         return popupContent[property];
     }


    render() {
        // I want to render some element from popupContent here
        <div>
            // <this.body /> // it's jsx format
            {this.body}
        </div>
    }
}

我在這里添加了工作示例JSfiddle ReactJS

您不必使用JSX。 如果這樣做,正確的方法是使用工廠。 您還可以在render方法中呈現常規HTML,以及使用花括號在代碼中使用普通javascript。

另外,我建議您映射和迭代數組中的所有項目,並在render方法中一一呈現它們

請參見下面的示例:

 var Login = React.createClass({ render: function() { return <div>{this.props.name}, logged in</div>; } }); // React with JSX ReactDOM.render(<Login name="John" />, document.getElementById('containerJSX')); // React without JSX var Login = React.createFactory(Login); ReactDOM.render(Login({ name: 'Tim' }), document.getElementById('containerNoJSX')); 

正如評論員所建議的那樣,您可能想要在構造函數中或在render方法本身中指定this.body

但是,如果我正確理解了您的意圖,則可以改用this.props.children 例如

<Popup><MyInnerComponent></Popup>

並在Popup render方法中

render() {
    <div>
        {this.props.children}
    </div>
}

實際上,React允許您使用具有JSX語法的變量來實例化組件。 您實際上應該能夠調用<this.body />並使其起作用; 但是,您不會這樣做,因為您this.bodycomponentDidUpdate方法之前才定義this.body ,這意味着它將在第一次渲染時未定義並破壞所有內容。 我建議為此而不是this.body使用本地組件狀態,並確保從頭開始定義它。

至少,在構造函數中this.body實例this.body某個值:

constructor(props) {
    super(props);
    this.body = 'Login';
}

只要this.body具有實際值,就可以使用<this.body />來渲染組件。 也許您只需要:

render() {
    return <div>
        {this.body ? <this.body /> : null}
    </div>
}

不過,在給出的示例中,您可以將componentDidMount的內容放到constructor ,因為構造函數是在第一次渲染傳遞之前調用的。

我認為您正在查看的是危險的SetInnerHtml

<div dangerouslySetInnerHTML={this.body} />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM