自动滚动到消息的底部

时间:2015-08-17 22:34:02

标签: javascript css reactjs

我正在开发一个聊天应用程序,每次我发送一条消息,我需要滚动到底部才能看到新消息。因此,与常规聊天一样,我需要提供用户可以查看最后消息的功能,而无需手动滚动到底部。

我正在使用React,有没有css方式?或者你能告诉我最好的方法吗?

让我给你看一些代码

这是主要成分

  render () {
    let messages = this.props.chatMessages.map((message) => {
      return <ChatItem info={message.info} me={message.me} player={message.player} message={message.message} />;
    });

    let chatForm;

    if (this.props.mode === 'player') {
      chatForm = <ChatForm onAddMessage={this.addMessage} />;
    }

    return <div className="Chat">
      <ul className="Chat__messages">{messages}</ul>
      <hr />
      <div>{chatForm}</div>
    </div>;
  }

这里是ChatItemChatForm组件

  render () {
    let item;
    const { message, player, me, info } = this.props;

    if (info) {
      item = <li><em>{message}</em></li>;
    }
    else if (me) {
      item = <li><strong>Me: {message}</strong></li>;
    }
    else {
      item = <li><strong>{player}:</strong> {message}</li>;
    }

    return item;
  }


  render () {
    return <div className="ChatForm">
      <input
        className="ChatForm__input"
        placeholder="Your message..."
        ref="newMessage"
        onKeyDown={this.onKeyDown}
        autofocus="true" />
    </div>;
  }

添加信息

我需要这样的东西http://codepen.io/TimPietrusky/pen/ylkFs

看看这部分

  // Scroll the latest line of output
  output.scrollTop(
    output[0].scrollHeight - output.height()
  );

我应该如何使其适应我在React上的代码?

1 个答案:

答案 0 :(得分:2)

一种方法是比较生命周期事件(如 public class MainActivity extends Activity implements AsyncResponse,AsyncResponse2 { EditText fullname,gender,city,mobileno; TextView originalname,reviewNumber; //for displaying in textfield before entering values(when loading) private static final String TAG_NAME = "fullname"; private static final String TAG_GENDER = "gender"; private static final String TAG_CITY = "city_name"; private static final String TAG_PHNO = "phone_number"; private static final String TAG_REVIEWNUM = "revcount"; RadioButton male,female; String numberToPass = "1" ;//default 1 for male //str photo upload ImageView imageView1, imageView2; //RoundImage roundedImage, roundedImage1; //private static int RESULT_LOAD_IMAGE = 1; //added //end photo upload Button submit; //str round img upload CircularBitmap c= new CircularBitmap(); Button pic; String selectedImagePath; ImageView image; //end round img upload @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); //str photo upload pic = (Button)findViewById(R.id.button1); image = (ImageView)findViewById(R.id.imageView1); //this the button which allows you to access the gallery pic.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { gallery(); } }); //end photo upload fullname=(EditText)findViewById(R.id.nameid); // gender=(EditText)findViewById(R.id.genderid); male=(RadioButton)findViewById(R.id.maleid); female=(RadioButton)findViewById(R.id.femaleid); city=(EditText)findViewById(R.id.cityid); mobileno=(EditText)findViewById(R.id.mobileid); originalname=(TextView)findViewById(R.id.originalnameid);//original name title reviewNumber=(TextView)findViewById(R.id.reviewNum); submit=(Button)findViewById(R.id.submitid); //to display fullname,gender,city,moblieno while loading(so outside buttonclick) String key1 = "saasvaap123"; String signupid1 = "8"; String url2 = "http://gooffers.in/omowebservices/index.php/webservice/Public_User/get_user_profile?"; //put the below lines outside button onclick since we load the values into edittext when opening the app CustomHttpClient2 task2 = new CustomHttpClient2(); task2.execute(url2,key1,signupid1); task2.delegate = MainActivity.this; //to send values on button click submit.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String fullname1= fullname.getText().toString(); // String gender1= gender.getText().toString(); String city1= city.getText().toString(); String mobileno1= mobileno.getText().toString(); String key1 = "saasvaap123"; String signupid1 = "3"; // String cityid1 = "3"; String originalname1= originalname.getText().toString(); // onRadioButtonClicked(numberToPasss); String url = "http://gooffers.in/omowebservices/index.php/webservice/Public_User/edit_user_profile?"; CustomHttpClient task = new CustomHttpClient(); task.execute(url,key1,signupid1,numberToPass,mobileno1,fullname1,city1); task.delegate = MainActivity.this; //mobile number validation if (!isValidMobNum(mobileno1)) { mobileno.setError("Enter valid mobile number!"); } // key=saasvaap123&signup_id=3&gender=1&phone_number=1234567890&fullname=saas&city_id=3 } }); } //close oncreate public void onRadioButtonClicked(View v) { switch (v.getId()) { case R.id.maleid: numberToPass = "1"; break; case R.id.femaleid: numberToPass = "2"; break; } } //str img upload //this allows you select one image from gallery public void gallery() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1); } //when starting activity for result and choose an image, the code will automatically continue here @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { if (requestCode == 1) { Uri current_ImageURI = data.getData(); selectedImagePath = getPath(current_ImageURI); image.setImageBitmap(c.circle(decodeSampledBitmap(new File(selectedImagePath), 400, 400),Color.rgb(255,255,255))); } } } public String getPath(Uri contentUri) { // we have to check for sdk version because from lollipop the retrieval of path is different if (Build.VERSION.SDK_INT < 21) { // can post image String[] proj = {MediaStore.Images.Media.DATA}; Cursor cursor = getApplicationContext().getContentResolver().query(contentUri, proj, null, null, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } else { String filePath = ""; String wholeID = DocumentsContract.getDocumentId(contentUri); // Split at colon, use second item in the array String id = wholeID.split(":")[1]; String[] column = {MediaStore.Images.Media.DATA}; // where id is equal to String sel = MediaStore.Images.Media._ID + "=?"; Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,column, sel, new String[]{id}, null); int columnIndex = cursor.getColumnIndex(column[0]); if (cursor.moveToFirst()) { filePath = cursor.getString(columnIndex); } cursor.close(); return filePath; } } public Bitmap decodeSampledBitmap(File res, int reqWidth, int reqHeight) { if (res != null) { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; try { FileInputStream stream2 = new FileInputStream(res); BitmapFactory.decodeStream(stream2, null, options); stream2.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // Calculate inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); o2.inJustDecodeBounds = false; FileInputStream stream = null; try { stream = new FileInputStream(res); } catch (FileNotFoundException e) { e.printStackTrace(); } Bitmap bitmap = BitmapFactory.decodeStream(stream, null, o2); try { stream.close(); } catch (IOException e) { e.printStackTrace(); } return bitmap; } else return null; } public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int halfHeight = height / 2; final int halfWidth = width / 2; // Calculate the largest inSampleSize value that is a power of 2 and keeps both // height and width larger than the requested height and width. while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { inSampleSize *= 2; } } return inSampleSize; } //end img upload //validating mobile num private boolean isValidMobNum(String mobileno1) { String MobilePattern = "[0-9]{10,13}"; //can enter upto 13 digits-change here if we need to increase the range of digits if(mobileno.getText().toString().matches(MobilePattern)) { Toast.makeText(getApplicationContext(), "phone number is valid", Toast.LENGTH_SHORT).show(); return true; } else if(!mobileno.getText().toString().matches(MobilePattern)) { Toast.makeText(getApplicationContext(), "Please enter valid 10 digit phone number", Toast.LENGTH_SHORT).show(); return false; } return false; } //str if empty validation // if(fullname1==null) // { // Toast.makeText(MainActivity.this,"Please enter your name!", Toast.LENGTH_SHORT).show(); // } // else if(gender1==null) // { // Toast.makeText(MainActivity.this,"Please enter your gender!", Toast.LENGTH_SHORT).show(); // } // else if(city1==null) // { // Toast.makeText(MainActivity.this,"Please enter your city name!", Toast.LENGTH_SHORT).show(); // } // else if(mobileno1==null) // { // Toast.makeText(MainActivity.this,"Please enter your contact number!", Toast.LENGTH_SHORT).show(); // } // else // { // Toast.makeText(MainActivity.this,"ok!", Toast.LENGTH_SHORT).show(); // } // //end if empty validation //edit private class CustomHttpClient extends AsyncTask<String, String, String>{ public AsyncResponse delegate=null; private String msg; @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); delegate.processFinish(result); } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); } @Override protected String doInBackground(String... params) { if(params == null) return null; // get url from params String url = params[0]; String key1 = params[1]; String signupid1 = params[2]; String gender1 = params[3]; String mobileno1 = params[4]; String fullname1 = params[5]; String city1 = params[6]; //key=saasvaap123&signup_id=3&gender=1&phone_number=1234567890&fullname=saas&city_id=3 ArrayList<NameValuePair> postParameters; postParameters = new ArrayList<NameValuePair>(); postParameters.add(new BasicNameValuePair("fullname",fullname1)); postParameters.add(new BasicNameValuePair("gender",gender1)); postParameters.add(new BasicNameValuePair("city_name",city1)); postParameters.add(new BasicNameValuePair("phone_number",mobileno1)); postParameters.add(new BasicNameValuePair("key",key1)); postParameters.add(new BasicNameValuePair("signup_id",signupid1)); // //str try { // create http connection HttpClient client = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); httppost.setEntity(new UrlEncodedFormEntity(postParameters)); // connect HttpResponse response = client.execute(httppost); // get response HttpEntity entity = response.getEntity(); if(entity != null){ return EntityUtils.toString(entity); } else{ return "No string."; } } catch(Exception e){ return "Network problem"; } } } public void processFinish (String output){ Toast.makeText(MainActivity.this,output, Toast.LENGTH_SHORT).show(); try{ JSONObject json=new JSONObject(output); // Integer success = json.getInt(SUCCESS); String msg = json.getString("message"); // String Status = json.getString("status"); // String userid = json.getString("userid"); // String usertype = json.getString("usertype"); // Integer userid=json.getInt("userid"); // String User_ID=String.valueOf(userid); // SharedPreferences sharedpreferences = getSharedPreferences(AQUASAN, Context.MODE_PRIVATE); // Editor editor = sharedpreferences.edit(); // editor.putString("ID", Employee_ID); // editor.commit(); //needed // String fullname = nameid.setText("saas"); // String gender = genderid.setText("0"); // String city_id = cityid.setText("0"); // String phone_number = mobileid.setText("0"); String a="Successfully Updated"; if(msg.compareTo(a)==0){ Toast.makeText(MainActivity.this,"Your profile has been successfully updated!", Toast.LENGTH_SHORT).show(); // Toast.makeText(MainActivity.this,msg, Toast.LENGTH_SHORT).show(); // startActivity(new Intent(Login.this, HomeScreen.class)); } else{ Toast.makeText(MainActivity.this,"Please enter the details correctly!", Toast.LENGTH_SHORT).show(); } }catch (JSONException e) { } } //edit //str customhttp2 private class CustomHttpClient2 extends AsyncTask<String, String, String>{ public AsyncResponse2 delegate=null; private String msg; @Override protected void onPostExecute(String result2) { // TODO Auto-generated method stub super.onPostExecute(result2); delegate.processFinish2(result2); } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); // fullname=(EditText)findViewById(R.id.nameid); // gender=(EditText)findViewById(R.id.genderid); // city=(EditText)findViewById(R.id.cityid); // mobileno=(EditText)findViewById(R.id.mobileid); } @Override protected String doInBackground(String... params) { if(params == null) return null; // get url from params String url2 = params[0]; String key1 = params[1]; String signupid1 = params[2]; // String gender1 = params[3]; // String mobileno1 = params[4]; // String fullname1 = params[5]; // String city1 = params[6]; //key=saasvaap123&signup_id=3&gender=1&phone_number=1234567890&fullname=saas&city_id=3 ArrayList<NameValuePair> postParameters; postParameters = new ArrayList<NameValuePair>(); // postParameters.add(new BasicNameValuePair("fullname",fullname1)); // postParameters.add(new BasicNameValuePair("gender",gender1)); // postParameters.add(new BasicNameValuePair("city_id",city1)); // postParameters.add(new BasicNameValuePair("phone_number",mobileno1)); postParameters.add(new BasicNameValuePair("key",key1)); postParameters.add(new BasicNameValuePair("signup_id",signupid1)); try { // create http connection HttpClient client = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url2); httppost.setEntity(new UrlEncodedFormEntity(postParameters)); // connect HttpResponse response = client.execute(httppost); // get response HttpEntity entity = response.getEntity(); if(entity != null){ return EntityUtils.toString(entity); } else{ return "No string."; } } catch(Exception e){ return "Network problem"; } } } public void processFinish2 (String output2){ Toast.makeText(MainActivity.this,output2, Toast.LENGTH_SHORT).show(); try{ JSONObject jsonResponse=new JSONObject(output2); JSONArray aJson = jsonResponse.getJSONArray("profile"); // Integer success = json.getInt(SUCCESS); // String msg = json.getString("message"); for(int i=0; i<aJson.length(); i++) { JSONObject json = aJson.getJSONObject(i); //str String strName = json.getString(TAG_NAME); String strGender = json.getString(TAG_GENDER); String strCity = json.getString(TAG_CITY); String strPhNo = json.getString(TAG_PHNO); String strOriginalName = json.getString(TAG_NAME); String strreviewNumber = json.getString(TAG_REVIEWNUM); fullname.setText(strName); // gender.setText(strGender); city.setText(strCity); mobileno.setText(strPhNo); originalname.setText(strOriginalName); reviewNumber.setText(strreviewNumber+"Reviews");//setting name to original name text-displayed while loading Toast.makeText(MainActivity.this,strGender, Toast.LENGTH_SHORT).show(); //end } }catch (JSONException e) { Toast.makeText(MainActivity.this,"Exception caught!", Toast.LENGTH_SHORT).show(); } } } )中的当前和上一个/下一个道具,如果添加了新消息则滚动到底部。例如:

componentDidUpdate