ReactJS(3)Handling Events - Conditional Rendering - List and Keys

ReactJS(3)Handling Events - Conditional Rendering - List and Keys

Handling Events
function ActionLink(){   //component
    function handleClick(e){
        e.preventDefault(); // return false
        console.log(’The link was clicked.');
    }

    return (
        <a href=“#” onClick={handleClick}>Click Me</a>
    );
}

Binding the event to this
class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
}

Conditional Rendering
https://facebook.github.io/react/docs/conditional-rendering.html
function UserGreeting(props) {
  return <h1>Welcome back!</h1>;
}

function GuestGreeting(props) {
  return <h1>Please sign up.</h1>;
}

function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <UserGreeting />;
  }
  return <GuestGreeting />;
}

ReactDOM.render(
  // Try changing to isLoggedIn={true}:
  <Greeting isLoggedIn={true} />,
  document.getElementById('root')
);

let will limit the variable scope
http://cookfront.github.io/2015/05/28/es6-let-const/

class LoginControl extends React.Component {
    constructor(props) {
        super(props);
        this.handleLoginClick = this.handleLoginClick.bind(this);
        this.handleLogoutClick = this.handleLogoutClick.bind(this);
        this.state = {isLoggedIn: false};
    }

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

    render() {
        const isLoggedIn = this.state.isLoggedIn;
        let button = null;
        if (isLoggedIn) {
            button = <LogoutButton onClick={this.handleLogoutClick} />;
        } else {
            button = <LoginButton onClick={this.handleLoginClick} />;
        }
        return ( <div> <Greeting isLoggedIn={isLoggedIn} /> {button} </div> );
    }
}

Inline If with && Operator
function Mailbox(props) {
  const unreadMessages = props.unreadMessages;
  return (
    <div>
      <h1>Hello!</h1>
      {unreadMessages.length > 0 &&
        <h2>
          You have {unreadMessages.length} unread messages.
        </h2>
      }
      {unreadMessages.length <= 0 &&
        <h2>
          No new messages
        </h2>
      }
    </div>
  );
}

//const messages = ['React', 'Re: React', 'Re:Re: React'];
const messages = [];
ReactDOM.render(
  <Mailbox unreadMessages={messages} />,
  document.getElementById('root')
);

We can inline if and else
{isLoggedIn ? ( <LogoutButton onClick={this.handleLogoutClick} /> ) : ( <LoginButton onClick={this.handleLoginClick} /> )}

Preventing Component from Rendering
function WarningBanner(props) {
    if (!props.warn) { return null; }
    return ( <div className="warning"> Warning! </div> );
}

if there is warn in props, system will ignore rendering the warning message.

Lists and Keys
https://facebook.github.io/react/docs/lists-and-keys.html

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((number) => number * 2);

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((numbers) =>
  <li>{numbers}</li>
);

ReactDOM.render(
  <ul>{listItems}</ul>,
  document.getElementById('root')
);

Basic List Component
const listItems = numbers.map((number) =>
    <li key={number.toString()}>
        {number}
    </li>
);

Keys
Keys is given to the elements inside the array to give the elements a stable identity.
const todoItems = todos.map((todo) =>
    <li key={todo.id}> {todo.text} </li>
);

For the one we do not have a unique ID, we can directly use the index of that list
const todoItems = todos.map((todo, index) =>
    <li key={index}> {todo.text} </li>
);

Extracting Components with Keys
Keys Only Be Unique Among Siblings




References:
https://facebook.github.io/react/docs/handling-events.html






猜你喜欢

转载自sillycat.iteye.com/blog/2377592