Прежде чем перейти к динамическим методам рендеринга, есть последний способ использовать встроенные условия JavaScript для рендеринга того, что вы хотите: <em><strong>трехмерный оператор</strong></em> . Тернарный оператор часто используется как ярлык для операторов <code>if/else</code> в JavaScript. Они не настолько устойчивы, как традиционные инструкции <code>if/else</code> , но они очень популярны среди разработчиков React. Одна из причин этого заключается в том, что JSX скомпилирован, <code>if/else</code> инструкции не могут быть вставлены непосредственно в код JSX. Возможно, вы заметили это несколько проблем назад - когда требовался оператор <code>if/else</code> , он всегда находился <em>за пределами</em> оператора <code>return</code> . Тернарные выражения могут быть отличной альтернативой, если вы хотите реализовать условную логику в своем JSX. Напомним, что тройной оператор состоит из трех частей, но вы можете комбинировать несколько тройных выражений. Вот основной синтаксис: <blockquote> состояние ? выражениеIfTrue: выражениеIfFalse </blockquote>
The code editor has three constants defined within the <code>CheckUserAge</code> component's <code>render()</code> method. They are called <code>buttonOne</code>, <code>buttonTwo</code>, and <code>buttonThree</code>. Each of these is assigned a simple JSX expression representing a button element. First, initialize the state of <code>CheckUserAge</code> with <code>input</code> and <code>userAge</code> both set to values of an empty string.
Once the component is rendering information to the page, users should have a way to interact with it. Within the component's <code>return</code> statement, set up a ternary expression that implements the following logic: when the page first loads, render the submit button, <code>buttonOne</code>, to the page. Then, when a user enters their age and clicks the button, render a different button based on the age. If a user enters a number less than <code>18</code>, render <code>buttonThree</code>. If a user enters a number greater than or equal to <code>18</code>, render <code>buttonTwo</code>.
- text: The <code>CheckUserAge</code> component's state should be initialized with a property of <code>userAge</code> and a property of <code>input</code>, both set to a value of an empty string.
- text: When a number of less than 18 is entered into the <code>input</code> element and the <code>button</code> is clicked, the <code>button</code>'s inner text should read <code>You Shall Not Pass</code>.
- text: When a number greater than or equal to 18 is entered into the <code>input</code> element and the <code>button</code> is clicked, the <code>button</code>'s inner text should read <code>You May Enter</code>.
- text: Once a number has been submitted, and the value of the <code>input</code> is once again changed, the <code>button</code> should return to reading <code>Submit</code>.