React學習筆記(四) 條件渲染與列表渲染


一、條件渲染

1、條件渲染

在 React 中,我們可以通過創建不同的組件封裝不同的行為,然后根據應用的狀態渲染對應狀態下的部分內容

// 定義組件封裝登陸行為
class SignIn extends React.Component {
    constructor(props) {
        super(props)
    }
    
    render() {
        return <h1>Please Sign In</h1>
    }
}

// 定義組件封裝注冊行為
class SignUp extends React.Component {
    constructor(props) {
        super(props)
    }
    
    render() {
        return <h1>Please Sign Up</h1>
    }
}

// 根據用戶是否已經登陸決定渲染哪個組件
class Greeting extends React.Component {
    constructor(props) {
        super(props)
    }

    render() {
        if (this.props.isSignUp) {
            return <SignIn />
        } else {
            return <SignUp />
        }
    }
}

ReactDOM.render(
    <Greeting isSignUp={false} />,
    document.getElementById('app')
);

2、阻止組件渲染

在某些情況下,我們希望可以隱藏元素,這時候我們需要讓 render() 返回 null 即可

class Warning extends React.Component {
    constructor(props) {
        super(props)
    }

    render() {
        if (this.props.isWaring) {
            return <span>Waring!</span>
        } else {
            return null
        }
    }
}

ReactDOM.render(
    <Warning isWarning={false}/>,
    document.getElementById('app')
);

3、元素變量

我們可以使用變量儲存元素,使得我們可以有條件地渲染組件的一部分

class LoginControl extends React.Component {
    constructor(props) {
        // 1、傳遞 props
        super(props);
        // 2、初始 state
        this.state = {isLoggedIn: false};
        // 3、為事件處理函數綁定組件實例
        this.handleLoginClick = this.handleLoginClick.bind(this);
        this.handleLogoutClick = this.handleLogoutClick.bind(this);
    }

    handleLoginClick() {
    	this.setState({isLoggedIn: true});
    }

    handleLogoutClick() {
    	this.setState({isLoggedIn: false});
    }

    render() {
        // 使用變量根據條件儲存元素
        let greeting;
        let button;

        if (this.state.isLoggedIn) {
            greeting = <h1>Now you are logged in!</h1>;
        	button = <button onClick={this.handleLogoutClick}>Log Out</button>;
        } else {
            greeting = <h1>Please log in!</h1>;
        	button = <button onClick={this.handleLoginClick}>Log In</button>;
        }

        return (
            <div>
                {greeting}
                {button}
            </div>
        );
    }
}

ReactDOM.render(
    <LoginControl isLoggedIn={false} />,
    document.getElementById('app')
);

二、列表渲染

1、渲染元素

在 React 組件中,我們可以通過 map() 方法快速渲染列表元素,我們先來看一個小例子

<!DOCTYPE html>
<html>

<head>
    <title>Demo</title>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone"></script>
</head>

<body>
    <div id="app"></div>

    <script type="text/babel">
        class ItemList extends React.Component {
            render() {
                const numbers = [1, 2, 3, 4, 5]
                const items = numbers.map((number)=>(<li>{ number }</li>))
                return (<ul>{ items }</ul>)
            }
        }

        ReactDOM.render(
            <ItemList />,
            document.getElementById('app')
        );
    </script>
</body>

</html>

2、key 屬性

在上面的例子中,雖然可以正常顯示元素,但是當我們打開控制台的時候,會看到有一條警告信息

Warning: Each child in a list should have a unique "key" prop.

我們可以通過給每個列表元素分配一個 key 屬性來解決上面這個問題

class ItemList extends React.Component {
    render() {
        const numbers = [1, 2, 3, 4, 5]
        const items = numbers.map((number)=>(
            <li key={ number.toString() }>
                { number }
            </li>
        ))
        return (
            <ul>{ items }</ul>
        )
    }
}

一個元素的 key 最好是這個元素在列表中擁有的獨一無二的字符串,萬不得已的情況下也可以使用元素索引

class ItemList extends React.Component {
    render() {
        const numbers = [1, 2, 3, 4, 5]
        const items = numbers.map((number, index)=>(
            <li key={ index }>
                { number }
            </li>
        ))
        return (
            <ul>{ items }</ul>
        )
    }
}

如果列表項目的順序會發生改變,那么不建議使用索引作為 key,因為這樣可能會導致性能問題,甚至會引起組件狀態的問題

在默認的情況下,即我們沒有顯式指定 key 時,React 將使用索引作為列表項目的 key

3、渲染組件

除了可以使用 map() 方法渲染多個元素,還可以使用 map() 渲染多個組件,請看一個例子

class TodoItem extends React.Component {
    constructor(props) {
        super(props)
    }

    render() {
        return ( <h3>{ this.props.title }</h3> )
    }
}

class TodoList extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            itemList: [
                {id: 0, title: 'Say Hello', isDone: true},
                {id: 1, title: 'Say Goodbye', isDone: false}
            ]
        }
    }

    render() {
        const todoItemList = this.state.itemList.map((item) => {
            if (!item.isDone) {
                return ( <li key={ item.id }><TodoItem title={ item.title } /></li> )
            }
        })

        return ( <ul>{ todoItemList }</ul> )
    }
}

ReactDOM.render(
    <TodoList />,
    document.getElementById('app')
)

【 閱讀更多 React 系列文章,請看 React學習筆記


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM